6211438058deb571a6d03c935582b8805240ff9a
[pandora-kernel.git] / drivers / net / wireless / ipw2200.c
1 /******************************************************************************
2
3   Copyright(c) 2003 - 2004 Intel Corporation. All rights reserved.
4
5   802.11 status code portion of this file from ethereal-0.10.6:
6     Copyright 2000, Axis Communications AB
7     Ethereal - Network traffic analyzer
8     By Gerald Combs <gerald@ethereal.com>
9     Copyright 1998 Gerald Combs
10
11   This program is free software; you can redistribute it and/or modify it
12   under the terms of version 2 of the GNU General Public License as
13   published by the Free Software Foundation.
14
15   This program is distributed in the hope that it will be useful, but WITHOUT
16   ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
17   FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
18   more details.
19
20   You should have received a copy of the GNU General Public License along with
21   this program; if not, write to the Free Software Foundation, Inc., 59
22   Temple Place - Suite 330, Boston, MA  02111-1307, USA.
23
24   The full GNU General Public License is included in this distribution in the
25   file called LICENSE.
26
27   Contact Information:
28   James P. Ketrenos <ipw2100-admin@linux.intel.com>
29   Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
30
31 ******************************************************************************/
32
33 #include "ipw2200.h"
34
35 #define IPW2200_VERSION "1.0.0"
36 #define DRV_DESCRIPTION "Intel(R) PRO/Wireless 2200/2915 Network Driver"
37 #define DRV_COPYRIGHT   "Copyright(c) 2003-2004 Intel Corporation"
38 #define DRV_VERSION     IPW2200_VERSION
39
40 MODULE_DESCRIPTION(DRV_DESCRIPTION);
41 MODULE_VERSION(DRV_VERSION);
42 MODULE_AUTHOR(DRV_COPYRIGHT);
43 MODULE_LICENSE("GPL");
44
45 static int debug = 0;
46 static int channel = 0;
47 static char *ifname;
48 static int mode = 0;
49
50 static u32 ipw_debug_level;
51 static int associate = 1;
52 static int auto_create = 1;
53 static int disable = 0;
54 static const char ipw_modes[] = {
55         'a', 'b', 'g', '?'
56 };
57
58 static void ipw_rx(struct ipw_priv *priv);
59 static int ipw_queue_tx_reclaim(struct ipw_priv *priv,
60                                 struct clx2_tx_queue *txq, int qindex);
61 static int ipw_queue_reset(struct ipw_priv *priv);
62
63 static int ipw_queue_tx_hcmd(struct ipw_priv *priv, int hcmd, void *buf,
64                              int len, int sync);
65
66 static void ipw_tx_queue_free(struct ipw_priv *);
67
68 static struct ipw_rx_queue *ipw_rx_queue_alloc(struct ipw_priv *);
69 static void ipw_rx_queue_free(struct ipw_priv *, struct ipw_rx_queue *);
70 static void ipw_rx_queue_replenish(void *);
71
72 static int ipw_up(struct ipw_priv *);
73 static void ipw_down(struct ipw_priv *);
74 static int ipw_config(struct ipw_priv *);
75 static int init_supported_rates(struct ipw_priv *priv, struct ipw_supported_rates *prates);
76
77 static u8 band_b_active_channel[MAX_B_CHANNELS] = {
78         1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0
79 };
80 static u8 band_a_active_channel[MAX_A_CHANNELS] = {
81         36, 40, 44, 48, 149, 153, 157, 161, 165, 52, 56, 60, 64, 0
82 };
83
84 static int is_valid_channel(int mode_mask, int channel)
85 {
86         int i;
87
88         if (!channel)
89                 return 0;
90
91         if (mode_mask & IEEE_A)
92                 for (i = 0; i < MAX_A_CHANNELS; i++)
93                         if (band_a_active_channel[i] == channel)
94                                 return IEEE_A;
95
96         if (mode_mask & (IEEE_B | IEEE_G))
97                 for (i = 0; i < MAX_B_CHANNELS; i++)
98                         if (band_b_active_channel[i] == channel)
99                                 return mode_mask & (IEEE_B | IEEE_G);
100
101         return 0;
102 }
103
104 static char *snprint_line(char *buf, size_t count,
105                           const u8 *data, u32 len, u32 ofs)
106 {
107         int out, i, j, l;
108         char c;
109
110         out = snprintf(buf, count, "%08X", ofs);
111
112         for (l = 0, i = 0; i < 2; i++) {
113                 out += snprintf(buf + out, count - out, " ");
114                 for (j = 0; j < 8 && l < len; j++, l++)
115                         out += snprintf(buf + out, count - out, "%02X ",
116                                         data[(i * 8 + j)]);
117                 for (; j < 8; j++)
118                         out += snprintf(buf + out, count - out, "   ");
119         }
120
121         out += snprintf(buf + out, count - out, " ");
122         for (l = 0, i = 0; i < 2; i++) {
123                 out += snprintf(buf + out, count - out, " ");
124                 for (j = 0; j < 8 && l < len; j++, l++) {
125                         c = data[(i * 8 + j)];
126                         if (!isascii(c) || !isprint(c))
127                                 c = '.';
128
129                         out += snprintf(buf + out, count - out, "%c", c);
130                 }
131
132                 for (; j < 8; j++)
133                         out += snprintf(buf + out, count - out, " ");
134         }
135
136         return buf;
137 }
138
139 static void printk_buf(int level, const u8 *data, u32 len)
140 {
141         char line[81];
142         u32 ofs = 0;
143         if (!(ipw_debug_level & level))
144                 return;
145
146         while (len) {
147                 printk(KERN_DEBUG "%s\n",
148                        snprint_line(line, sizeof(line), &data[ofs],
149                                     min(len, 16U), ofs));
150                 ofs += 16;
151                 len -= min(len, 16U);
152         }
153 }
154
155 static u32 _ipw_read_reg32(struct ipw_priv *priv, u32 reg);
156 #define ipw_read_reg32(a, b) _ipw_read_reg32(a, b)
157
158 static u8 _ipw_read_reg8(struct ipw_priv *ipw, u32 reg);
159 #define ipw_read_reg8(a, b) _ipw_read_reg8(a, b)
160
161 static void _ipw_write_reg8(struct ipw_priv *priv, u32 reg, u8 value);
162 static inline void ipw_write_reg8(struct ipw_priv *a, u32 b, u8 c)
163 {
164         IPW_DEBUG_IO("%s %d: write_indirect8(0x%08X, 0x%08X)\n", __FILE__, __LINE__, (u32)(b), (u32)(c));
165         _ipw_write_reg8(a, b, c);
166 }
167
168 static void _ipw_write_reg16(struct ipw_priv *priv, u32 reg, u16 value);
169 static inline void ipw_write_reg16(struct ipw_priv *a, u32 b, u16 c)
170 {
171         IPW_DEBUG_IO("%s %d: write_indirect16(0x%08X, 0x%08X)\n", __FILE__, __LINE__, (u32)(b), (u32)(c));
172         _ipw_write_reg16(a, b, c);
173 }
174
175 static void _ipw_write_reg32(struct ipw_priv *priv, u32 reg, u32 value);
176 static inline void ipw_write_reg32(struct ipw_priv *a, u32 b, u32 c)
177 {
178         IPW_DEBUG_IO("%s %d: write_indirect32(0x%08X, 0x%08X)\n", __FILE__, __LINE__, (u32)(b), (u32)(c));
179         _ipw_write_reg32(a, b, c);
180 }
181
182 #define _ipw_write8(ipw, ofs, val) writeb((val), (ipw)->hw_base + (ofs))
183 #define ipw_write8(ipw, ofs, val) \
184  IPW_DEBUG_IO("%s %d: write_direct8(0x%08X, 0x%08X)\n", __FILE__, __LINE__, (u32)(ofs), (u32)(val)); \
185  _ipw_write8(ipw, ofs, val)
186
187 #define _ipw_write16(ipw, ofs, val) writew((val), (ipw)->hw_base + (ofs))
188 #define ipw_write16(ipw, ofs, val) \
189  IPW_DEBUG_IO("%s %d: write_direct16(0x%08X, 0x%08X)\n", __FILE__, __LINE__, (u32)(ofs), (u32)(val)); \
190  _ipw_write16(ipw, ofs, val)
191
192 #define _ipw_write32(ipw, ofs, val) writel((val), (ipw)->hw_base + (ofs))
193 #define ipw_write32(ipw, ofs, val) \
194  IPW_DEBUG_IO("%s %d: write_direct32(0x%08X, 0x%08X)\n", __FILE__, __LINE__, (u32)(ofs), (u32)(val)); \
195  _ipw_write32(ipw, ofs, val)
196
197 #define _ipw_read8(ipw, ofs) readb((ipw)->hw_base + (ofs))
198 static inline u8 __ipw_read8(char *f, u32 l, struct ipw_priv *ipw, u32 ofs) {
199         IPW_DEBUG_IO("%s %d: read_direct8(0x%08X)\n", f, l, (u32)(ofs));
200         return _ipw_read8(ipw, ofs);
201 }
202 #define ipw_read8(ipw, ofs) __ipw_read8(__FILE__, __LINE__, ipw, ofs)
203
204 #define _ipw_read16(ipw, ofs) readw((ipw)->hw_base + (ofs))
205 static inline u16 __ipw_read16(char *f, u32 l, struct ipw_priv *ipw, u32 ofs) {
206         IPW_DEBUG_IO("%s %d: read_direct16(0x%08X)\n", f, l, (u32)(ofs));
207         return _ipw_read16(ipw, ofs);
208 }
209 #define ipw_read16(ipw, ofs) __ipw_read16(__FILE__, __LINE__, ipw, ofs)
210
211 #define _ipw_read32(ipw, ofs) readl((ipw)->hw_base + (ofs))
212 static inline u32 __ipw_read32(char *f, u32 l, struct ipw_priv *ipw, u32 ofs) {
213         IPW_DEBUG_IO("%s %d: read_direct32(0x%08X)\n", f, l, (u32)(ofs));
214         return _ipw_read32(ipw, ofs);
215 }
216 #define ipw_read32(ipw, ofs) __ipw_read32(__FILE__, __LINE__, ipw, ofs)
217
218 static void _ipw_read_indirect(struct ipw_priv *, u32, u8 *, int);
219 #define ipw_read_indirect(a, b, c, d) \
220         IPW_DEBUG_IO("%s %d: read_inddirect(0x%08X) %d bytes\n", __FILE__, __LINE__, (u32)(b), d); \
221         _ipw_read_indirect(a, b, c, d)
222
223 static void _ipw_write_indirect(struct ipw_priv *priv, u32 addr, u8 *data, int num);
224 #define ipw_write_indirect(a, b, c, d) \
225         IPW_DEBUG_IO("%s %d: write_indirect(0x%08X) %d bytes\n", __FILE__, __LINE__, (u32)(b), d); \
226         _ipw_write_indirect(a, b, c, d)
227
228 /* indirect write s */
229 static void _ipw_write_reg32(struct ipw_priv *priv, u32 reg,
230                              u32 value)
231 {
232         IPW_DEBUG_IO(" %p : reg = 0x%8X : value = 0x%8X\n",
233                      priv, reg, value);
234         _ipw_write32(priv, CX2_INDIRECT_ADDR, reg);
235         _ipw_write32(priv, CX2_INDIRECT_DATA, value);
236 }
237
238
239 static void _ipw_write_reg8(struct ipw_priv *priv, u32 reg, u8 value)
240 {
241         IPW_DEBUG_IO(" reg = 0x%8X : value = 0x%8X\n", reg, value);
242         _ipw_write32(priv, CX2_INDIRECT_ADDR, reg & CX2_INDIRECT_ADDR_MASK);
243         _ipw_write8(priv, CX2_INDIRECT_DATA, value);
244         IPW_DEBUG_IO(" reg = 0x%8lX : value = 0x%8X\n",
245                      (unsigned long)(priv->hw_base + CX2_INDIRECT_DATA),
246                      value);
247 }
248
249 static void _ipw_write_reg16(struct ipw_priv *priv, u32 reg,
250                              u16 value)
251 {
252         IPW_DEBUG_IO(" reg = 0x%8X : value = 0x%8X\n", reg, value);
253         _ipw_write32(priv, CX2_INDIRECT_ADDR, reg & CX2_INDIRECT_ADDR_MASK);
254         _ipw_write16(priv, CX2_INDIRECT_DATA, value);
255 }
256
257 /* indirect read s */
258
259 static u8 _ipw_read_reg8(struct ipw_priv *priv, u32 reg)
260 {
261         u32 word;
262         _ipw_write32(priv, CX2_INDIRECT_ADDR, reg & CX2_INDIRECT_ADDR_MASK);
263         IPW_DEBUG_IO(" reg = 0x%8X : \n", reg);
264         word = _ipw_read32(priv, CX2_INDIRECT_DATA);
265         return (word >> ((reg & 0x3)*8)) & 0xff;
266 }
267
268 static u32 _ipw_read_reg32(struct ipw_priv *priv, u32 reg)
269 {
270         u32 value;
271
272         IPW_DEBUG_IO("%p : reg = 0x%08x\n", priv, reg);
273
274         _ipw_write32(priv, CX2_INDIRECT_ADDR, reg);
275         value = _ipw_read32(priv, CX2_INDIRECT_DATA);
276         IPW_DEBUG_IO(" reg = 0x%4X : value = 0x%4x \n", reg, value);
277         return value;
278 }
279
280 /* iterative/auto-increment 32 bit reads and writes */
281 static void _ipw_read_indirect(struct ipw_priv *priv, u32 addr, u8 * buf,
282                                int num)
283 {
284         u32 aligned_addr = addr & CX2_INDIRECT_ADDR_MASK;
285         u32 dif_len = addr - aligned_addr;
286         u32 aligned_len;
287         u32 i;
288
289         IPW_DEBUG_IO("addr = %i, buf = %p, num = %i\n", addr, buf, num);
290
291         /* Read the first nibble byte by byte */
292         if (unlikely(dif_len)) {
293                 /* Start reading at aligned_addr + dif_len */
294                 _ipw_write32(priv, CX2_INDIRECT_ADDR, aligned_addr);
295                 for (i = dif_len; i < 4; i++, buf++)
296                         *buf = _ipw_read8(priv, CX2_INDIRECT_DATA + i);
297                 num -= dif_len;
298                 aligned_addr += 4;
299         }
300
301         /* Read DWs through autoinc register */
302         _ipw_write32(priv, CX2_AUTOINC_ADDR, aligned_addr);
303         aligned_len = num & CX2_INDIRECT_ADDR_MASK;
304         for (i = 0; i < aligned_len; i += 4, buf += 4, aligned_addr += 4)
305                 *(u32*)buf = ipw_read32(priv, CX2_AUTOINC_DATA);
306
307         /* Copy the last nibble */
308         dif_len = num - aligned_len;
309         _ipw_write32(priv, CX2_INDIRECT_ADDR, aligned_addr);
310         for (i = 0; i < dif_len; i++, buf++)
311                 *buf = ipw_read8(priv, CX2_INDIRECT_DATA + i);
312 }
313
314 static void _ipw_write_indirect(struct ipw_priv *priv, u32 addr, u8 *buf,
315                                 int num)
316 {
317         u32 aligned_addr = addr & CX2_INDIRECT_ADDR_MASK;
318         u32 dif_len = addr - aligned_addr;
319         u32 aligned_len;
320         u32 i;
321
322         IPW_DEBUG_IO("addr = %i, buf = %p, num = %i\n", addr, buf, num);
323
324         /* Write the first nibble byte by byte */
325         if (unlikely(dif_len)) {
326                 /* Start writing at aligned_addr + dif_len */
327                 _ipw_write32(priv, CX2_INDIRECT_ADDR, aligned_addr);
328                 for (i = dif_len; i < 4; i++, buf++)
329                         _ipw_write8(priv, CX2_INDIRECT_DATA + i, *buf);
330                 num -= dif_len;
331                 aligned_addr += 4;
332         }
333
334         /* Write DWs through autoinc register */
335         _ipw_write32(priv, CX2_AUTOINC_ADDR, aligned_addr);
336         aligned_len = num & CX2_INDIRECT_ADDR_MASK;
337         for (i = 0; i < aligned_len; i += 4, buf += 4, aligned_addr += 4)
338                 _ipw_write32(priv, CX2_AUTOINC_DATA, *(u32*)buf);
339
340         /* Copy the last nibble */
341         dif_len = num - aligned_len;
342         _ipw_write32(priv, CX2_INDIRECT_ADDR, aligned_addr);
343         for (i = 0; i < dif_len; i++, buf++)
344                 _ipw_write8(priv, CX2_INDIRECT_DATA + i, *buf);
345 }
346
347 static void ipw_write_direct(struct ipw_priv *priv, u32 addr, void *buf,
348                              int num)
349 {
350         memcpy_toio((priv->hw_base + addr), buf, num);
351 }
352
353 static inline void ipw_set_bit(struct ipw_priv *priv, u32 reg, u32 mask)
354 {
355         ipw_write32(priv, reg, ipw_read32(priv, reg) | mask);
356 }
357
358 static inline void ipw_clear_bit(struct ipw_priv *priv, u32 reg, u32 mask)
359 {
360         ipw_write32(priv, reg, ipw_read32(priv, reg) & ~mask);
361 }
362
363 static inline void ipw_enable_interrupts(struct ipw_priv *priv)
364 {
365         if (priv->status & STATUS_INT_ENABLED)
366                 return;
367         priv->status |= STATUS_INT_ENABLED;
368         ipw_write32(priv, CX2_INTA_MASK_R, CX2_INTA_MASK_ALL);
369 }
370
371 static inline void ipw_disable_interrupts(struct ipw_priv *priv)
372 {
373         if (!(priv->status & STATUS_INT_ENABLED))
374                 return;
375         priv->status &= ~STATUS_INT_ENABLED;
376         ipw_write32(priv, CX2_INTA_MASK_R, ~CX2_INTA_MASK_ALL);
377 }
378
379 static char *ipw_error_desc(u32 val)
380 {
381         switch (val) {
382         case IPW_FW_ERROR_OK:
383                 return "ERROR_OK";
384         case IPW_FW_ERROR_FAIL:
385                 return "ERROR_FAIL";
386         case IPW_FW_ERROR_MEMORY_UNDERFLOW:
387                 return "MEMORY_UNDERFLOW";
388         case IPW_FW_ERROR_MEMORY_OVERFLOW:
389                 return "MEMORY_OVERFLOW";
390         case IPW_FW_ERROR_BAD_PARAM:
391                 return "ERROR_BAD_PARAM";
392         case IPW_FW_ERROR_BAD_CHECKSUM:
393                 return "ERROR_BAD_CHECKSUM";
394         case IPW_FW_ERROR_NMI_INTERRUPT:
395                 return "ERROR_NMI_INTERRUPT";
396         case IPW_FW_ERROR_BAD_DATABASE:
397                 return "ERROR_BAD_DATABASE";
398         case IPW_FW_ERROR_ALLOC_FAIL:
399                 return "ERROR_ALLOC_FAIL";
400         case IPW_FW_ERROR_DMA_UNDERRUN:
401                 return "ERROR_DMA_UNDERRUN";
402         case IPW_FW_ERROR_DMA_STATUS:
403                 return "ERROR_DMA_STATUS";
404         case IPW_FW_ERROR_DINOSTATUS_ERROR:
405                 return "ERROR_DINOSTATUS_ERROR";
406         case IPW_FW_ERROR_EEPROMSTATUS_ERROR:
407                 return "ERROR_EEPROMSTATUS_ERROR";
408         case IPW_FW_ERROR_SYSASSERT:
409                 return "ERROR_SYSASSERT";
410         case IPW_FW_ERROR_FATAL_ERROR:
411                 return "ERROR_FATALSTATUS_ERROR";
412         default:
413                 return "UNKNOWNSTATUS_ERROR";
414         }
415 }
416
417 static void ipw_dump_nic_error_log(struct ipw_priv *priv)
418 {
419         u32 desc, time, blink1, blink2, ilink1, ilink2, idata, i, count, base;
420
421         base = ipw_read32(priv, IPWSTATUS_ERROR_LOG);
422         count = ipw_read_reg32(priv, base);
423
424         if (ERROR_START_OFFSET <= count * ERROR_ELEM_SIZE) {
425                 IPW_ERROR("Start IPW Error Log Dump:\n");
426                 IPW_ERROR("Status: 0x%08X, Config: %08X\n",
427                           priv->status, priv->config);
428         }
429
430         for (i = ERROR_START_OFFSET;
431              i <= count * ERROR_ELEM_SIZE;
432              i += ERROR_ELEM_SIZE) {
433                 desc   = ipw_read_reg32(priv, base + i);
434                 time   = ipw_read_reg32(priv, base + i + 1*sizeof(u32));
435                 blink1 = ipw_read_reg32(priv, base + i + 2*sizeof(u32));
436                 blink2 = ipw_read_reg32(priv, base + i + 3*sizeof(u32));
437                 ilink1 = ipw_read_reg32(priv, base + i + 4*sizeof(u32));
438                 ilink2 = ipw_read_reg32(priv, base + i + 5*sizeof(u32));
439                 idata =  ipw_read_reg32(priv, base + i + 6*sizeof(u32));
440
441                 IPW_ERROR(
442                         "%s %i 0x%08x  0x%08x  0x%08x  0x%08x  0x%08x\n",
443                         ipw_error_desc(desc), time, blink1, blink2,
444                         ilink1, ilink2, idata);
445         }
446 }
447
448 static void ipw_dump_nic_event_log(struct ipw_priv *priv)
449 {
450         u32 ev, time, data, i, count, base;
451
452         base = ipw_read32(priv, IPW_EVENT_LOG);
453         count = ipw_read_reg32(priv, base);
454
455         if (EVENT_START_OFFSET <= count * EVENT_ELEM_SIZE)
456                 IPW_ERROR("Start IPW Event Log Dump:\n");
457
458         for (i = EVENT_START_OFFSET;
459              i <= count * EVENT_ELEM_SIZE;
460              i += EVENT_ELEM_SIZE) {
461                 ev = ipw_read_reg32(priv, base + i);
462                 time  = ipw_read_reg32(priv, base + i + 1*sizeof(u32));
463                 data  = ipw_read_reg32(priv, base + i + 2*sizeof(u32));
464
465 #ifdef CONFIG_IPW_DEBUG
466                 IPW_ERROR("%i\t0x%08x\t%i\n", time, data, ev);
467 #endif
468         }
469 }
470
471 static int ipw_get_ordinal(struct ipw_priv *priv, u32 ord, void *val,
472                            u32 *len)
473 {
474         u32 addr, field_info, field_len, field_count, total_len;
475
476         IPW_DEBUG_ORD("ordinal = %i\n", ord);
477
478         if (!priv || !val || !len) {
479                 IPW_DEBUG_ORD("Invalid argument\n");
480                 return -EINVAL;
481         }
482
483         /* verify device ordinal tables have been initialized */
484         if (!priv->table0_addr || !priv->table1_addr || !priv->table2_addr) {
485                 IPW_DEBUG_ORD("Access ordinals before initialization\n");
486                 return -EINVAL;
487         }
488
489         switch (IPW_ORD_TABLE_ID_MASK & ord) {
490         case IPW_ORD_TABLE_0_MASK:
491                 /*
492                  * TABLE 0: Direct access to a table of 32 bit values
493                  *
494                  * This is a very simple table with the data directly
495                  * read from the table
496                  */
497
498                 /* remove the table id from the ordinal */
499                 ord &= IPW_ORD_TABLE_VALUE_MASK;
500
501                 /* boundary check */
502                 if (ord > priv->table0_len) {
503                         IPW_DEBUG_ORD("ordinal value (%i) longer then "
504                                       "max (%i)\n", ord, priv->table0_len);
505                         return -EINVAL;
506                 }
507
508                 /* verify we have enough room to store the value */
509                 if (*len < sizeof(u32)) {
510                         IPW_DEBUG_ORD("ordinal buffer length too small, "
511                                       "need %zd\n", sizeof(u32));
512                         return -EINVAL;
513                 }
514
515                 IPW_DEBUG_ORD("Reading TABLE0[%i] from offset 0x%08x\n",
516                               ord, priv->table0_addr + (ord  << 2));
517
518                 *len = sizeof(u32);
519                 ord <<= 2;
520                 *((u32 *)val) = ipw_read32(priv, priv->table0_addr + ord);
521                 break;
522
523         case IPW_ORD_TABLE_1_MASK:
524                 /*
525                  * TABLE 1: Indirect access to a table of 32 bit values
526                  *
527                  * This is a fairly large table of u32 values each
528                  * representing starting addr for the data (which is
529                  * also a u32)
530                  */
531
532                 /* remove the table id from the ordinal */
533                 ord &= IPW_ORD_TABLE_VALUE_MASK;
534
535                 /* boundary check */
536                 if (ord > priv->table1_len) {
537                         IPW_DEBUG_ORD("ordinal value too long\n");
538                         return -EINVAL;
539                 }
540
541                 /* verify we have enough room to store the value */
542                 if (*len < sizeof(u32)) {
543                         IPW_DEBUG_ORD("ordinal buffer length too small, "
544                                       "need %zd\n", sizeof(u32));
545                         return -EINVAL;
546                 }
547
548                 *((u32 *)val) = ipw_read_reg32(priv, (priv->table1_addr + (ord << 2)));
549                 *len = sizeof(u32);
550                 break;
551
552         case IPW_ORD_TABLE_2_MASK:
553                 /*
554                  * TABLE 2: Indirect access to a table of variable sized values
555                  *
556                  * This table consist of six values, each containing
557                  *     - dword containing the starting offset of the data
558                  *     - dword containing the lengh in the first 16bits
559                  *       and the count in the second 16bits
560                  */
561
562                 /* remove the table id from the ordinal */
563                 ord &= IPW_ORD_TABLE_VALUE_MASK;
564
565                 /* boundary check */
566                 if (ord > priv->table2_len) {
567                         IPW_DEBUG_ORD("ordinal value too long\n");
568                         return -EINVAL;
569                 }
570
571                 /* get the address of statistic */
572                 addr = ipw_read_reg32(priv, priv->table2_addr + (ord << 3));
573
574                 /* get the second DW of statistics ;
575                  * two 16-bit words - first is length, second is count */
576                 field_info = ipw_read_reg32(priv, priv->table2_addr + (ord << 3) + sizeof(u32));
577
578                 /* get each entry length */
579                 field_len = *((u16 *)&field_info);
580
581                 /* get number of entries */
582                 field_count = *(((u16 *)&field_info) + 1);
583
584                 /* abort if not enought memory */
585                 total_len = field_len * field_count;
586                 if (total_len > *len) {
587                         *len = total_len;
588                         return -EINVAL;
589                 }
590
591                 *len = total_len;
592                 if (!total_len)
593                         return 0;
594
595                 IPW_DEBUG_ORD("addr = 0x%08x, total_len = %i, "
596                               "field_info = 0x%08x\n",
597                               addr, total_len, field_info);
598                 ipw_read_indirect(priv, addr, val, total_len);
599                 break;
600
601         default:
602                 IPW_DEBUG_ORD("Invalid ordinal!\n");
603                 return -EINVAL;
604
605         }
606
607
608         return 0;
609 }
610
611 static void ipw_init_ordinals(struct ipw_priv *priv)
612 {
613         priv->table0_addr = IPW_ORDINALS_TABLE_LOWER;
614         priv->table0_len = ipw_read32(priv, priv->table0_addr);
615
616         IPW_DEBUG_ORD("table 0 offset at 0x%08x, len = %i\n",
617                       priv->table0_addr, priv->table0_len);
618
619         priv->table1_addr = ipw_read32(priv, IPW_ORDINALS_TABLE_1);
620         priv->table1_len = ipw_read_reg32(priv, priv->table1_addr);
621
622         IPW_DEBUG_ORD("table 1 offset at 0x%08x, len = %i\n",
623                       priv->table1_addr, priv->table1_len);
624
625         priv->table2_addr = ipw_read32(priv, IPW_ORDINALS_TABLE_2);
626         priv->table2_len = ipw_read_reg32(priv, priv->table2_addr);
627         priv->table2_len &= 0x0000ffff; /* use first two bytes */
628
629         IPW_DEBUG_ORD("table 2 offset at 0x%08x, len = %i\n",
630                       priv->table2_addr, priv->table2_len);
631
632 }
633
634 /*
635  * The following adds a new attribute to the sysfs representation
636  * of this device driver (i.e. a new file in /sys/bus/pci/drivers/ipw/)
637  * used for controling the debug level.
638  *
639  * See the level definitions in ipw for details.
640  */
641 static ssize_t show_debug_level(struct device_driver *d, char *buf)
642 {
643         return sprintf(buf, "0x%08X\n", ipw_debug_level);
644 }
645 static ssize_t store_debug_level(struct device_driver *d,
646                                 const char *buf, size_t count)
647 {
648         char *p = (char *)buf;
649         u32 val;
650
651         if (p[1] == 'x' || p[1] == 'X' || p[0] == 'x' || p[0] == 'X') {
652                 p++;
653                 if (p[0] == 'x' || p[0] == 'X')
654                         p++;
655                 val = simple_strtoul(p, &p, 16);
656         } else
657                 val = simple_strtoul(p, &p, 10);
658         if (p == buf)
659                 printk(KERN_INFO DRV_NAME
660                        ": %s is not in hex or decimal form.\n", buf);
661         else
662                 ipw_debug_level = val;
663
664         return strnlen(buf, count);
665 }
666
667 static DRIVER_ATTR(debug_level, S_IWUSR | S_IRUGO,
668                    show_debug_level, store_debug_level);
669
670 static ssize_t show_status(struct device *d,
671                         struct device_attribute *attr, char *buf)
672 {
673         struct ipw_priv *p = d->driver_data;
674         return sprintf(buf, "0x%08x\n", (int)p->status);
675 }
676 static DEVICE_ATTR(status, S_IRUGO, show_status, NULL);
677
678 static ssize_t show_cfg(struct device *d, struct device_attribute *attr,
679                         char *buf)
680 {
681         struct ipw_priv *p = d->driver_data;
682         return sprintf(buf, "0x%08x\n", (int)p->config);
683 }
684 static DEVICE_ATTR(cfg, S_IRUGO, show_cfg, NULL);
685
686 static ssize_t show_nic_type(struct device *d,
687                         struct device_attribute *attr, char *buf)
688 {
689         struct ipw_priv *p = d->driver_data;
690         u8 type = p->eeprom[EEPROM_NIC_TYPE];
691
692         switch (type) {
693         case EEPROM_NIC_TYPE_STANDARD:
694                 return sprintf(buf, "STANDARD\n");
695         case EEPROM_NIC_TYPE_DELL:
696                 return sprintf(buf, "DELL\n");
697         case EEPROM_NIC_TYPE_FUJITSU:
698                 return sprintf(buf, "FUJITSU\n");
699         case EEPROM_NIC_TYPE_IBM:
700                 return sprintf(buf, "IBM\n");
701         case EEPROM_NIC_TYPE_HP:
702                 return sprintf(buf, "HP\n");
703         }
704
705         return sprintf(buf, "UNKNOWN\n");
706 }
707 static DEVICE_ATTR(nic_type, S_IRUGO, show_nic_type, NULL);
708
709 static ssize_t dump_error_log(struct device *d,
710                 struct device_attribute *attr, const char *buf, size_t count)
711 {
712         char *p = (char *)buf;
713
714         if (p[0] == '1')
715                 ipw_dump_nic_error_log((struct ipw_priv*)d->driver_data);
716
717         return strnlen(buf, count);
718 }
719 static DEVICE_ATTR(dump_errors, S_IWUSR, NULL, dump_error_log);
720
721 static ssize_t dump_event_log(struct device *d,
722                 struct device_attribute *attr, const char *buf, size_t count)
723 {
724         char *p = (char *)buf;
725
726         if (p[0] == '1')
727                 ipw_dump_nic_event_log((struct ipw_priv*)d->driver_data);
728
729         return strnlen(buf, count);
730 }
731 static DEVICE_ATTR(dump_events, S_IWUSR, NULL, dump_event_log);
732
733 static ssize_t show_ucode_version(struct device *d,
734                         struct device_attribute *attr, char *buf)
735 {
736         u32 len = sizeof(u32), tmp = 0;
737         struct ipw_priv *p = d->driver_data;
738
739         if(ipw_get_ordinal(p, IPW_ORD_STAT_UCODE_VERSION, &tmp, &len))
740                 return 0;
741
742         return sprintf(buf, "0x%08x\n", tmp);
743 }
744 static DEVICE_ATTR(ucode_version, S_IWUSR|S_IRUGO, show_ucode_version, NULL);
745
746 static ssize_t show_rtc(struct device *d, struct device_attribute *attr,
747                         char *buf)
748 {
749         u32 len = sizeof(u32), tmp = 0;
750         struct ipw_priv *p = d->driver_data;
751
752         if(ipw_get_ordinal(p, IPW_ORD_STAT_RTC, &tmp, &len))
753                 return 0;
754
755         return sprintf(buf, "0x%08x\n", tmp);
756 }
757 static DEVICE_ATTR(rtc, S_IWUSR|S_IRUGO, show_rtc, NULL);
758
759 /*
760  * Add a device attribute to view/control the delay between eeprom
761  * operations.
762  */
763 static ssize_t show_eeprom_delay(struct device *d,
764                         struct device_attribute *attr, char *buf)
765 {
766         int n = ((struct ipw_priv*)d->driver_data)->eeprom_delay;
767         return sprintf(buf, "%i\n", n);
768 }
769 static ssize_t store_eeprom_delay(struct device *d,
770                         struct device_attribute *attr, const char *buf,
771                         size_t count)
772 {
773         struct ipw_priv *p = d->driver_data;
774         sscanf(buf, "%i", &p->eeprom_delay);
775         return strnlen(buf, count);
776 }
777 static DEVICE_ATTR(eeprom_delay, S_IWUSR|S_IRUGO,
778                    show_eeprom_delay,store_eeprom_delay);
779
780 static ssize_t show_command_event_reg(struct device *d,
781                         struct device_attribute *attr, char *buf)
782 {
783         u32 reg = 0;
784         struct ipw_priv *p = d->driver_data;
785
786         reg = ipw_read_reg32(p, CX2_INTERNAL_CMD_EVENT);
787         return sprintf(buf, "0x%08x\n", reg);
788 }
789 static ssize_t store_command_event_reg(struct device *d,
790                                 struct device_attribute *attr, const char *buf,
791                                 size_t count)
792 {
793         u32 reg;
794         struct ipw_priv *p = d->driver_data;
795
796         sscanf(buf, "%x", &reg);
797         ipw_write_reg32(p, CX2_INTERNAL_CMD_EVENT, reg);
798         return strnlen(buf, count);
799 }
800 static DEVICE_ATTR(command_event_reg, S_IWUSR|S_IRUGO,
801                    show_command_event_reg,store_command_event_reg);
802
803 static ssize_t show_mem_gpio_reg(struct device *d,
804                                 struct device_attribute *attr, char *buf)
805 {
806         u32 reg = 0;
807         struct ipw_priv *p = d->driver_data;
808
809         reg = ipw_read_reg32(p, 0x301100);
810         return sprintf(buf, "0x%08x\n", reg);
811 }
812 static ssize_t store_mem_gpio_reg(struct device *d,
813                         struct device_attribute *attr, const char *buf,
814                         size_t count)
815 {
816         u32 reg;
817         struct ipw_priv *p = d->driver_data;
818
819         sscanf(buf, "%x", &reg);
820         ipw_write_reg32(p, 0x301100, reg);
821         return strnlen(buf, count);
822 }
823 static DEVICE_ATTR(mem_gpio_reg, S_IWUSR|S_IRUGO,
824                    show_mem_gpio_reg,store_mem_gpio_reg);
825
826 static ssize_t show_indirect_dword(struct device *d,
827                                 struct device_attribute *attr, char *buf)
828 {
829         u32 reg = 0;
830         struct ipw_priv *priv = d->driver_data;
831         if (priv->status & STATUS_INDIRECT_DWORD)
832                 reg = ipw_read_reg32(priv, priv->indirect_dword);
833         else
834                 reg = 0;
835
836         return sprintf(buf, "0x%08x\n", reg);
837 }
838 static ssize_t store_indirect_dword(struct device *d,
839                                 struct device_attribute *attr, const char *buf,
840                                 size_t count)
841 {
842         struct ipw_priv *priv = d->driver_data;
843
844         sscanf(buf, "%x", &priv->indirect_dword);
845         priv->status |= STATUS_INDIRECT_DWORD;
846         return strnlen(buf, count);
847 }
848 static DEVICE_ATTR(indirect_dword, S_IWUSR|S_IRUGO,
849                    show_indirect_dword,store_indirect_dword);
850
851 static ssize_t show_indirect_byte(struct device *d,
852                         struct device_attribute *attr, char *buf)
853 {
854         u8 reg = 0;
855         struct ipw_priv *priv = d->driver_data;
856         if (priv->status & STATUS_INDIRECT_BYTE)
857                 reg = ipw_read_reg8(priv, priv->indirect_byte);
858         else
859                 reg = 0;
860
861         return sprintf(buf, "0x%02x\n", reg);
862 }
863 static ssize_t store_indirect_byte(struct device *d,
864                                 struct device_attribute *attr, const char *buf,
865                                 size_t count)
866 {
867         struct ipw_priv *priv = d->driver_data;
868
869         sscanf(buf, "%x", &priv->indirect_byte);
870         priv->status |= STATUS_INDIRECT_BYTE;
871         return strnlen(buf, count);
872 }
873 static DEVICE_ATTR(indirect_byte, S_IWUSR|S_IRUGO,
874                    show_indirect_byte, store_indirect_byte);
875
876 static ssize_t show_direct_dword(struct device *d,
877                                 struct device_attribute *attr, char *buf)
878 {
879         u32 reg = 0;
880         struct ipw_priv *priv = d->driver_data;
881
882         if (priv->status & STATUS_DIRECT_DWORD)
883                 reg = ipw_read32(priv, priv->direct_dword);
884         else
885                 reg = 0;
886
887         return sprintf(buf, "0x%08x\n", reg);
888 }
889 static ssize_t store_direct_dword(struct device *d,
890                         struct device_attribute *attr, const char *buf,
891                         size_t count)
892 {
893         struct ipw_priv *priv = d->driver_data;
894
895         sscanf(buf, "%x", &priv->direct_dword);
896         priv->status |= STATUS_DIRECT_DWORD;
897         return strnlen(buf, count);
898 }
899 static DEVICE_ATTR(direct_dword, S_IWUSR|S_IRUGO,
900                    show_direct_dword,store_direct_dword);
901
902
903 static inline int rf_kill_active(struct ipw_priv *priv)
904 {
905         if (0 == (ipw_read32(priv, 0x30) & 0x10000))
906                 priv->status |= STATUS_RF_KILL_HW;
907         else
908                 priv->status &= ~STATUS_RF_KILL_HW;
909
910         return (priv->status & STATUS_RF_KILL_HW) ? 1 : 0;
911 }
912
913 static ssize_t show_rf_kill(struct device *d, struct device_attribute *attr,
914                                 char *buf)
915 {
916         /* 0 - RF kill not enabled
917            1 - SW based RF kill active (sysfs)
918            2 - HW based RF kill active
919            3 - Both HW and SW baed RF kill active */
920         struct ipw_priv *priv = d->driver_data;
921         int val = ((priv->status & STATUS_RF_KILL_SW) ? 0x1 : 0x0) |
922                 (rf_kill_active(priv) ? 0x2 : 0x0);
923         return sprintf(buf, "%i\n", val);
924 }
925
926 static int ipw_radio_kill_sw(struct ipw_priv *priv, int disable_radio)
927 {
928         if ((disable_radio ? 1 : 0) ==
929             (priv->status & STATUS_RF_KILL_SW ? 1 : 0))
930                 return 0 ;
931
932         IPW_DEBUG_RF_KILL("Manual SW RF Kill set to: RADIO  %s\n",
933                           disable_radio ? "OFF" : "ON");
934
935         if (disable_radio) {
936                 priv->status |= STATUS_RF_KILL_SW;
937
938                 if (priv->workqueue) {
939                         cancel_delayed_work(&priv->request_scan);
940                 }
941                 wake_up_interruptible(&priv->wait_command_queue);
942                 queue_work(priv->workqueue, &priv->down);
943         } else {
944                 priv->status &= ~STATUS_RF_KILL_SW;
945                 if (rf_kill_active(priv)) {
946                         IPW_DEBUG_RF_KILL("Can not turn radio back on - "
947                                           "disabled by HW switch\n");
948                         /* Make sure the RF_KILL check timer is running */
949                         cancel_delayed_work(&priv->rf_kill);
950                         queue_delayed_work(priv->workqueue, &priv->rf_kill,
951                                            2 * HZ);
952                 } else
953                         queue_work(priv->workqueue, &priv->up);
954         }
955
956         return 1;
957 }
958
959 static ssize_t store_rf_kill(struct device *d,  struct device_attribute *attr,
960                                 const char *buf, size_t count)
961 {
962         struct ipw_priv *priv = d->driver_data;
963
964         ipw_radio_kill_sw(priv, buf[0] == '1');
965
966         return count;
967 }
968 static DEVICE_ATTR(rf_kill, S_IWUSR|S_IRUGO, show_rf_kill, store_rf_kill);
969
970 static void ipw_irq_tasklet(struct ipw_priv *priv)
971 {
972         u32 inta, inta_mask, handled = 0;
973         unsigned long flags;
974         int rc = 0;
975
976         spin_lock_irqsave(&priv->lock, flags);
977
978         inta = ipw_read32(priv, CX2_INTA_RW);
979         inta_mask = ipw_read32(priv, CX2_INTA_MASK_R);
980         inta &= (CX2_INTA_MASK_ALL & inta_mask);
981
982         /* Add any cached INTA values that need to be handled */
983         inta |= priv->isr_inta;
984
985         /* handle all the justifications for the interrupt */
986         if (inta & CX2_INTA_BIT_RX_TRANSFER) {
987                 ipw_rx(priv);
988                 handled |= CX2_INTA_BIT_RX_TRANSFER;
989         }
990
991         if (inta & CX2_INTA_BIT_TX_CMD_QUEUE) {
992                 IPW_DEBUG_HC("Command completed.\n");
993                 rc = ipw_queue_tx_reclaim( priv, &priv->txq_cmd, -1);
994                 priv->status &= ~STATUS_HCMD_ACTIVE;
995                 wake_up_interruptible(&priv->wait_command_queue);
996                 handled |= CX2_INTA_BIT_TX_CMD_QUEUE;
997         }
998
999         if (inta & CX2_INTA_BIT_TX_QUEUE_1) {
1000                 IPW_DEBUG_TX("TX_QUEUE_1\n");
1001                 rc = ipw_queue_tx_reclaim( priv, &priv->txq[0], 0);
1002                 handled |= CX2_INTA_BIT_TX_QUEUE_1;
1003         }
1004
1005         if (inta & CX2_INTA_BIT_TX_QUEUE_2) {
1006                 IPW_DEBUG_TX("TX_QUEUE_2\n");
1007                 rc = ipw_queue_tx_reclaim( priv, &priv->txq[1], 1);
1008                 handled |= CX2_INTA_BIT_TX_QUEUE_2;
1009         }
1010
1011         if (inta & CX2_INTA_BIT_TX_QUEUE_3) {
1012                 IPW_DEBUG_TX("TX_QUEUE_3\n");
1013                 rc = ipw_queue_tx_reclaim( priv, &priv->txq[2], 2);
1014                 handled |= CX2_INTA_BIT_TX_QUEUE_3;
1015         }
1016
1017         if (inta & CX2_INTA_BIT_TX_QUEUE_4) {
1018                 IPW_DEBUG_TX("TX_QUEUE_4\n");
1019                 rc = ipw_queue_tx_reclaim( priv, &priv->txq[3], 3);
1020                 handled |= CX2_INTA_BIT_TX_QUEUE_4;
1021         }
1022
1023         if (inta & CX2_INTA_BIT_STATUS_CHANGE) {
1024                 IPW_WARNING("STATUS_CHANGE\n");
1025                 handled |= CX2_INTA_BIT_STATUS_CHANGE;
1026         }
1027
1028         if (inta & CX2_INTA_BIT_BEACON_PERIOD_EXPIRED) {
1029                 IPW_WARNING("TX_PERIOD_EXPIRED\n");
1030                 handled |= CX2_INTA_BIT_BEACON_PERIOD_EXPIRED;
1031         }
1032
1033         if (inta & CX2_INTA_BIT_SLAVE_MODE_HOST_CMD_DONE) {
1034                 IPW_WARNING("HOST_CMD_DONE\n");
1035                 handled |= CX2_INTA_BIT_SLAVE_MODE_HOST_CMD_DONE;
1036         }
1037
1038         if (inta & CX2_INTA_BIT_FW_INITIALIZATION_DONE) {
1039                 IPW_WARNING("FW_INITIALIZATION_DONE\n");
1040                 handled |= CX2_INTA_BIT_FW_INITIALIZATION_DONE;
1041         }
1042
1043         if (inta & CX2_INTA_BIT_FW_CARD_DISABLE_PHY_OFF_DONE) {
1044                 IPW_WARNING("PHY_OFF_DONE\n");
1045                 handled |= CX2_INTA_BIT_FW_CARD_DISABLE_PHY_OFF_DONE;
1046         }
1047
1048         if (inta & CX2_INTA_BIT_RF_KILL_DONE) {
1049                 IPW_DEBUG_RF_KILL("RF_KILL_DONE\n");
1050                 priv->status |= STATUS_RF_KILL_HW;
1051                 wake_up_interruptible(&priv->wait_command_queue);
1052                 netif_carrier_off(priv->net_dev);
1053                 netif_stop_queue(priv->net_dev);
1054                 cancel_delayed_work(&priv->request_scan);
1055                 queue_delayed_work(priv->workqueue, &priv->rf_kill, 2 * HZ);
1056                 handled |= CX2_INTA_BIT_RF_KILL_DONE;
1057         }
1058
1059         if (inta & CX2_INTA_BIT_FATAL_ERROR) {
1060                 IPW_ERROR("Firmware error detected.  Restarting.\n");
1061 #ifdef CONFIG_IPW_DEBUG
1062                 if (ipw_debug_level & IPW_DL_FW_ERRORS) {
1063                         ipw_dump_nic_error_log(priv);
1064                         ipw_dump_nic_event_log(priv);
1065                 }
1066 #endif
1067                 queue_work(priv->workqueue, &priv->adapter_restart);
1068                 handled |= CX2_INTA_BIT_FATAL_ERROR;
1069         }
1070
1071         if (inta & CX2_INTA_BIT_PARITY_ERROR) {
1072                 IPW_ERROR("Parity error\n");
1073                 handled |= CX2_INTA_BIT_PARITY_ERROR;
1074         }
1075
1076         if (handled != inta) {
1077                 IPW_ERROR("Unhandled INTA bits 0x%08x\n",
1078                                 inta & ~handled);
1079         }
1080
1081         /* enable all interrupts */
1082         ipw_enable_interrupts(priv);
1083
1084         spin_unlock_irqrestore(&priv->lock, flags);
1085 }
1086
1087 #ifdef CONFIG_IPW_DEBUG
1088 #define IPW_CMD(x) case IPW_CMD_ ## x : return #x
1089 static char *get_cmd_string(u8 cmd)
1090 {
1091         switch (cmd) {
1092                 IPW_CMD(HOST_COMPLETE);
1093                 IPW_CMD(POWER_DOWN);
1094                 IPW_CMD(SYSTEM_CONFIG);
1095                 IPW_CMD(MULTICAST_ADDRESS);
1096                 IPW_CMD(SSID);
1097                 IPW_CMD(ADAPTER_ADDRESS);
1098                 IPW_CMD(PORT_TYPE);
1099                 IPW_CMD(RTS_THRESHOLD);
1100                 IPW_CMD(FRAG_THRESHOLD);
1101                 IPW_CMD(POWER_MODE);
1102                 IPW_CMD(WEP_KEY);
1103                 IPW_CMD(TGI_TX_KEY);
1104                 IPW_CMD(SCAN_REQUEST);
1105                 IPW_CMD(SCAN_REQUEST_EXT);
1106                 IPW_CMD(ASSOCIATE);
1107                 IPW_CMD(SUPPORTED_RATES);
1108                 IPW_CMD(SCAN_ABORT);
1109                 IPW_CMD(TX_FLUSH);
1110                 IPW_CMD(QOS_PARAMETERS);
1111                 IPW_CMD(DINO_CONFIG);
1112                 IPW_CMD(RSN_CAPABILITIES);
1113                 IPW_CMD(RX_KEY);
1114                 IPW_CMD(CARD_DISABLE);
1115                 IPW_CMD(SEED_NUMBER);
1116                 IPW_CMD(TX_POWER);
1117                 IPW_CMD(COUNTRY_INFO);
1118                 IPW_CMD(AIRONET_INFO);
1119                 IPW_CMD(AP_TX_POWER);
1120                 IPW_CMD(CCKM_INFO);
1121                 IPW_CMD(CCX_VER_INFO);
1122                 IPW_CMD(SET_CALIBRATION);
1123                 IPW_CMD(SENSITIVITY_CALIB);
1124                 IPW_CMD(RETRY_LIMIT);
1125                 IPW_CMD(IPW_PRE_POWER_DOWN);
1126                 IPW_CMD(VAP_BEACON_TEMPLATE);
1127                 IPW_CMD(VAP_DTIM_PERIOD);
1128                 IPW_CMD(EXT_SUPPORTED_RATES);
1129                 IPW_CMD(VAP_LOCAL_TX_PWR_CONSTRAINT);
1130                 IPW_CMD(VAP_QUIET_INTERVALS);
1131                 IPW_CMD(VAP_CHANNEL_SWITCH);
1132                 IPW_CMD(VAP_MANDATORY_CHANNELS);
1133                 IPW_CMD(VAP_CELL_PWR_LIMIT);
1134                 IPW_CMD(VAP_CF_PARAM_SET);
1135                 IPW_CMD(VAP_SET_BEACONING_STATE);
1136                 IPW_CMD(MEASUREMENT);
1137                 IPW_CMD(POWER_CAPABILITY);
1138                 IPW_CMD(SUPPORTED_CHANNELS);
1139                 IPW_CMD(TPC_REPORT);
1140                 IPW_CMD(WME_INFO);
1141                 IPW_CMD(PRODUCTION_COMMAND);
1142         default:
1143                 return "UNKNOWN";
1144         }
1145 }
1146 #endif /* CONFIG_IPW_DEBUG */
1147
1148 #define HOST_COMPLETE_TIMEOUT HZ
1149 static int ipw_send_cmd(struct ipw_priv *priv, struct host_cmd *cmd)
1150 {
1151         int rc = 0;
1152
1153         if (priv->status & STATUS_HCMD_ACTIVE) {
1154                 IPW_ERROR("Already sending a command\n");
1155                 return -1;
1156         }
1157
1158         priv->status |= STATUS_HCMD_ACTIVE;
1159
1160         IPW_DEBUG_HC("Sending %s command (#%d), %d bytes\n",
1161                      get_cmd_string(cmd->cmd), cmd->cmd, cmd->len);
1162         printk_buf(IPW_DL_HOST_COMMAND, (u8*)cmd->param, cmd->len);
1163
1164         rc = ipw_queue_tx_hcmd(priv, cmd->cmd, &cmd->param, cmd->len, 0);
1165         if (rc)
1166                 return rc;
1167
1168         rc = wait_event_interruptible_timeout(
1169                 priv->wait_command_queue, !(priv->status & STATUS_HCMD_ACTIVE),
1170                 HOST_COMPLETE_TIMEOUT);
1171         if (rc == 0) {
1172                 IPW_DEBUG_INFO("Command completion failed out after %dms.\n",
1173                                jiffies_to_msecs(HOST_COMPLETE_TIMEOUT));
1174                 priv->status &= ~STATUS_HCMD_ACTIVE;
1175                 return -EIO;
1176         }
1177         if (priv->status & STATUS_RF_KILL_MASK) {
1178                 IPW_DEBUG_INFO("Command aborted due to RF Kill Switch\n");
1179                 return -EIO;
1180         }
1181
1182         return 0;
1183 }
1184
1185 static int ipw_send_host_complete(struct ipw_priv *priv)
1186 {
1187         struct host_cmd cmd = {
1188                 .cmd = IPW_CMD_HOST_COMPLETE,
1189                 .len = 0
1190         };
1191
1192         if (!priv) {
1193                 IPW_ERROR("Invalid args\n");
1194                 return -1;
1195         }
1196
1197         if (ipw_send_cmd(priv, &cmd)) {
1198                 IPW_ERROR("failed to send HOST_COMPLETE command\n");
1199                 return -1;
1200         }
1201
1202         return 0;
1203 }
1204
1205 static int ipw_send_system_config(struct ipw_priv *priv,
1206                                   struct ipw_sys_config *config)
1207 {
1208         struct host_cmd cmd = {
1209                 .cmd = IPW_CMD_SYSTEM_CONFIG,
1210                 .len = sizeof(*config)
1211         };
1212
1213         if (!priv || !config) {
1214                 IPW_ERROR("Invalid args\n");
1215                 return -1;
1216         }
1217
1218         memcpy(&cmd.param,config,sizeof(*config));
1219         if (ipw_send_cmd(priv, &cmd)) {
1220                 IPW_ERROR("failed to send SYSTEM_CONFIG command\n");
1221                 return -1;
1222         }
1223
1224         return 0;
1225 }
1226
1227 static int ipw_send_ssid(struct ipw_priv *priv, u8 *ssid, int len)
1228 {
1229         struct host_cmd cmd = {
1230                 .cmd = IPW_CMD_SSID,
1231                 .len = min(len, IW_ESSID_MAX_SIZE)
1232         };
1233
1234         if (!priv || !ssid) {
1235                 IPW_ERROR("Invalid args\n");
1236                 return -1;
1237         }
1238
1239         memcpy(&cmd.param, ssid, cmd.len);
1240         if (ipw_send_cmd(priv, &cmd)) {
1241                 IPW_ERROR("failed to send SSID command\n");
1242                 return -1;
1243         }
1244
1245         return 0;
1246 }
1247
1248 static int ipw_send_adapter_address(struct ipw_priv *priv, u8 *mac)
1249 {
1250         struct host_cmd cmd = {
1251                 .cmd = IPW_CMD_ADAPTER_ADDRESS,
1252                 .len = ETH_ALEN
1253         };
1254
1255         if (!priv || !mac) {
1256                 IPW_ERROR("Invalid args\n");
1257                 return -1;
1258         }
1259
1260         IPW_DEBUG_INFO("%s: Setting MAC to " MAC_FMT "\n",
1261                        priv->net_dev->name, MAC_ARG(mac));
1262
1263         memcpy(&cmd.param, mac, ETH_ALEN);
1264
1265         if (ipw_send_cmd(priv, &cmd)) {
1266                 IPW_ERROR("failed to send ADAPTER_ADDRESS command\n");
1267                 return -1;
1268         }
1269
1270         return 0;
1271 }
1272
1273 static void ipw_adapter_restart(void *adapter)
1274 {
1275         struct ipw_priv *priv = adapter;
1276
1277         if (priv->status & STATUS_RF_KILL_MASK)
1278                 return;
1279
1280         ipw_down(priv);
1281         if (ipw_up(priv)) {
1282                 IPW_ERROR("Failed to up device\n");
1283                 return;
1284         }
1285 }
1286
1287
1288
1289
1290 #define IPW_SCAN_CHECK_WATCHDOG (5 * HZ)
1291
1292 static void ipw_scan_check(void *data)
1293 {
1294         struct ipw_priv *priv = data;
1295         if (priv->status & (STATUS_SCANNING | STATUS_SCAN_ABORTING)) {
1296                 IPW_DEBUG_SCAN("Scan completion watchdog resetting "
1297                                "adapter (%dms).\n",
1298                                IPW_SCAN_CHECK_WATCHDOG / 100);
1299                 ipw_adapter_restart(priv);
1300         }
1301 }
1302
1303 static int ipw_send_scan_request_ext(struct ipw_priv *priv,
1304                                      struct ipw_scan_request_ext *request)
1305 {
1306         struct host_cmd cmd = {
1307                 .cmd = IPW_CMD_SCAN_REQUEST_EXT,
1308                 .len = sizeof(*request)
1309         };
1310
1311         if (!priv || !request) {
1312                 IPW_ERROR("Invalid args\n");
1313                 return -1;
1314         }
1315
1316         memcpy(&cmd.param,request,sizeof(*request));
1317         if (ipw_send_cmd(priv, &cmd)) {
1318                 IPW_ERROR("failed to send SCAN_REQUEST_EXT command\n");
1319                 return -1;
1320         }
1321
1322         queue_delayed_work(priv->workqueue, &priv->scan_check,
1323                            IPW_SCAN_CHECK_WATCHDOG);
1324         return 0;
1325 }
1326
1327 static int ipw_send_scan_abort(struct ipw_priv *priv)
1328 {
1329         struct host_cmd cmd = {
1330                 .cmd = IPW_CMD_SCAN_ABORT,
1331                 .len = 0
1332         };
1333
1334         if (!priv) {
1335                 IPW_ERROR("Invalid args\n");
1336                 return -1;
1337         }
1338
1339         if (ipw_send_cmd(priv, &cmd)) {
1340                 IPW_ERROR("failed to send SCAN_ABORT command\n");
1341                 return -1;
1342         }
1343
1344         return 0;
1345 }
1346
1347 static int ipw_set_sensitivity(struct ipw_priv *priv, u16 sens)
1348 {
1349         struct host_cmd cmd = {
1350                 .cmd = IPW_CMD_SENSITIVITY_CALIB,
1351                 .len = sizeof(struct ipw_sensitivity_calib)
1352         };
1353         struct ipw_sensitivity_calib *calib = (struct ipw_sensitivity_calib *)
1354                 &cmd.param;
1355         calib->beacon_rssi_raw = sens;
1356         if (ipw_send_cmd(priv, &cmd)) {
1357                 IPW_ERROR("failed to send SENSITIVITY CALIB command\n");
1358                 return -1;
1359         }
1360
1361         return 0;
1362 }
1363
1364 static int ipw_send_associate(struct ipw_priv *priv,
1365                               struct ipw_associate *associate)
1366 {
1367         struct host_cmd cmd = {
1368                 .cmd = IPW_CMD_ASSOCIATE,
1369                 .len = sizeof(*associate)
1370         };
1371
1372         if (!priv || !associate) {
1373                 IPW_ERROR("Invalid args\n");
1374                 return -1;
1375         }
1376
1377         memcpy(&cmd.param,associate,sizeof(*associate));
1378         if (ipw_send_cmd(priv, &cmd)) {
1379                 IPW_ERROR("failed to send ASSOCIATE command\n");
1380                 return -1;
1381         }
1382
1383         return 0;
1384 }
1385
1386 static int ipw_send_supported_rates(struct ipw_priv *priv,
1387                                     struct ipw_supported_rates *rates)
1388 {
1389         struct host_cmd cmd = {
1390                 .cmd = IPW_CMD_SUPPORTED_RATES,
1391                 .len = sizeof(*rates)
1392         };
1393
1394         if (!priv || !rates) {
1395                 IPW_ERROR("Invalid args\n");
1396                 return -1;
1397         }
1398
1399         memcpy(&cmd.param,rates,sizeof(*rates));
1400         if (ipw_send_cmd(priv, &cmd)) {
1401                 IPW_ERROR("failed to send SUPPORTED_RATES command\n");
1402                 return -1;
1403         }
1404
1405         return 0;
1406 }
1407
1408 static int ipw_set_random_seed(struct ipw_priv *priv)
1409 {
1410         struct host_cmd cmd = {
1411                 .cmd = IPW_CMD_SEED_NUMBER,
1412                 .len = sizeof(u32)
1413         };
1414
1415         if (!priv) {
1416                 IPW_ERROR("Invalid args\n");
1417                 return -1;
1418         }
1419
1420         get_random_bytes(&cmd.param, sizeof(u32));
1421
1422         if (ipw_send_cmd(priv, &cmd)) {
1423                 IPW_ERROR("failed to send SEED_NUMBER command\n");
1424                 return -1;
1425         }
1426
1427         return 0;
1428 }
1429
1430 #if 0
1431 static int ipw_send_card_disable(struct ipw_priv *priv, u32 phy_off)
1432 {
1433         struct host_cmd cmd = {
1434                 .cmd = IPW_CMD_CARD_DISABLE,
1435                 .len = sizeof(u32)
1436         };
1437
1438         if (!priv) {
1439                 IPW_ERROR("Invalid args\n");
1440                 return -1;
1441         }
1442
1443         *((u32*)&cmd.param) = phy_off;
1444
1445         if (ipw_send_cmd(priv, &cmd)) {
1446                 IPW_ERROR("failed to send CARD_DISABLE command\n");
1447                 return -1;
1448         }
1449
1450         return 0;
1451 }
1452 #endif
1453
1454 static int ipw_send_tx_power(struct ipw_priv *priv,
1455                              struct ipw_tx_power *power)
1456 {
1457         struct host_cmd cmd = {
1458                 .cmd = IPW_CMD_TX_POWER,
1459                 .len = sizeof(*power)
1460         };
1461
1462         if (!priv || !power) {
1463                 IPW_ERROR("Invalid args\n");
1464                 return -1;
1465         }
1466
1467         memcpy(&cmd.param,power,sizeof(*power));
1468         if (ipw_send_cmd(priv, &cmd)) {
1469                 IPW_ERROR("failed to send TX_POWER command\n");
1470                 return -1;
1471         }
1472
1473         return 0;
1474 }
1475
1476 static int ipw_send_rts_threshold(struct ipw_priv *priv, u16 rts)
1477 {
1478         struct ipw_rts_threshold rts_threshold = {
1479                 .rts_threshold = rts,
1480         };
1481         struct host_cmd cmd = {
1482                 .cmd = IPW_CMD_RTS_THRESHOLD,
1483                 .len = sizeof(rts_threshold)
1484         };
1485
1486         if (!priv) {
1487                 IPW_ERROR("Invalid args\n");
1488                 return -1;
1489         }
1490
1491         memcpy(&cmd.param, &rts_threshold, sizeof(rts_threshold));
1492         if (ipw_send_cmd(priv, &cmd)) {
1493                 IPW_ERROR("failed to send RTS_THRESHOLD command\n");
1494                 return -1;
1495         }
1496
1497         return 0;
1498 }
1499
1500 static int ipw_send_frag_threshold(struct ipw_priv *priv, u16 frag)
1501 {
1502         struct ipw_frag_threshold frag_threshold = {
1503                 .frag_threshold = frag,
1504         };
1505         struct host_cmd cmd = {
1506                 .cmd = IPW_CMD_FRAG_THRESHOLD,
1507                 .len = sizeof(frag_threshold)
1508         };
1509
1510         if (!priv) {
1511                 IPW_ERROR("Invalid args\n");
1512                 return -1;
1513         }
1514
1515         memcpy(&cmd.param, &frag_threshold, sizeof(frag_threshold));
1516         if (ipw_send_cmd(priv, &cmd)) {
1517                 IPW_ERROR("failed to send FRAG_THRESHOLD command\n");
1518                 return -1;
1519         }
1520
1521         return 0;
1522 }
1523
1524 static int ipw_send_power_mode(struct ipw_priv *priv, u32 mode)
1525 {
1526         struct host_cmd cmd = {
1527                 .cmd = IPW_CMD_POWER_MODE,
1528                 .len = sizeof(u32)
1529         };
1530         u32 *param = (u32*)(&cmd.param);
1531
1532         if (!priv) {
1533                 IPW_ERROR("Invalid args\n");
1534                 return -1;
1535         }
1536
1537         /* If on battery, set to 3, if AC set to CAM, else user
1538          * level */
1539         switch (mode) {
1540         case IPW_POWER_BATTERY:
1541                 *param = IPW_POWER_INDEX_3;
1542                 break;
1543         case IPW_POWER_AC:
1544                 *param = IPW_POWER_MODE_CAM;
1545                 break;
1546         default:
1547                 *param = mode;
1548                 break;
1549         }
1550
1551         if (ipw_send_cmd(priv, &cmd)) {
1552                 IPW_ERROR("failed to send POWER_MODE command\n");
1553                 return -1;
1554         }
1555
1556         return 0;
1557 }
1558
1559 /*
1560  * The IPW device contains a Microwire compatible EEPROM that stores
1561  * various data like the MAC address.  Usually the firmware has exclusive
1562  * access to the eeprom, but during device initialization (before the
1563  * device driver has sent the HostComplete command to the firmware) the
1564  * device driver has read access to the EEPROM by way of indirect addressing
1565  * through a couple of memory mapped registers.
1566  *
1567  * The following is a simplified implementation for pulling data out of the
1568  * the eeprom, along with some helper functions to find information in
1569  * the per device private data's copy of the eeprom.
1570  *
1571  * NOTE: To better understand how these functions work (i.e what is a chip
1572  *       select and why do have to keep driving the eeprom clock?), read
1573  *       just about any data sheet for a Microwire compatible EEPROM.
1574  */
1575
1576 /* write a 32 bit value into the indirect accessor register */
1577 static inline void eeprom_write_reg(struct ipw_priv *p, u32 data)
1578 {
1579         ipw_write_reg32(p, FW_MEM_REG_EEPROM_ACCESS, data);
1580
1581         /* the eeprom requires some time to complete the operation */
1582         udelay(p->eeprom_delay);
1583
1584         return;
1585 }
1586
1587 /* perform a chip select operation */
1588 static inline void eeprom_cs(struct ipw_priv* priv)
1589 {
1590         eeprom_write_reg(priv,0);
1591         eeprom_write_reg(priv,EEPROM_BIT_CS);
1592         eeprom_write_reg(priv,EEPROM_BIT_CS|EEPROM_BIT_SK);
1593         eeprom_write_reg(priv,EEPROM_BIT_CS);
1594 }
1595
1596 /* perform a chip select operation */
1597 static inline void eeprom_disable_cs(struct ipw_priv* priv)
1598 {
1599         eeprom_write_reg(priv,EEPROM_BIT_CS);
1600         eeprom_write_reg(priv,0);
1601         eeprom_write_reg(priv,EEPROM_BIT_SK);
1602 }
1603
1604 /* push a single bit down to the eeprom */
1605 static inline void eeprom_write_bit(struct ipw_priv *p,u8 bit)
1606 {
1607         int d = ( bit ? EEPROM_BIT_DI : 0);
1608         eeprom_write_reg(p,EEPROM_BIT_CS|d);
1609         eeprom_write_reg(p,EEPROM_BIT_CS|d|EEPROM_BIT_SK);
1610 }
1611
1612 /* push an opcode followed by an address down to the eeprom */
1613 static void eeprom_op(struct ipw_priv* priv, u8 op, u8 addr)
1614 {
1615         int i;
1616
1617         eeprom_cs(priv);
1618         eeprom_write_bit(priv,1);
1619         eeprom_write_bit(priv,op&2);
1620         eeprom_write_bit(priv,op&1);
1621         for ( i=7; i>=0; i-- ) {
1622                 eeprom_write_bit(priv,addr&(1<<i));
1623         }
1624 }
1625
1626 /* pull 16 bits off the eeprom, one bit at a time */
1627 static u16 eeprom_read_u16(struct ipw_priv* priv, u8 addr)
1628 {
1629         int i;
1630         u16 r=0;
1631
1632         /* Send READ Opcode */
1633         eeprom_op(priv,EEPROM_CMD_READ,addr);
1634
1635         /* Send dummy bit */
1636         eeprom_write_reg(priv,EEPROM_BIT_CS);
1637
1638         /* Read the byte off the eeprom one bit at a time */
1639         for ( i=0; i<16; i++ ) {
1640                 u32 data = 0;
1641                 eeprom_write_reg(priv,EEPROM_BIT_CS|EEPROM_BIT_SK);
1642                 eeprom_write_reg(priv,EEPROM_BIT_CS);
1643                 data = ipw_read_reg32(priv,FW_MEM_REG_EEPROM_ACCESS);
1644                 r = (r<<1) | ((data & EEPROM_BIT_DO)?1:0);
1645         }
1646
1647         /* Send another dummy bit */
1648         eeprom_write_reg(priv,0);
1649         eeprom_disable_cs(priv);
1650
1651         return r;
1652 }
1653
1654 /* helper function for pulling the mac address out of the private */
1655 /* data's copy of the eeprom data                                 */
1656 static void eeprom_parse_mac(struct ipw_priv* priv, u8* mac)
1657 {
1658         u8* ee = (u8*)priv->eeprom;
1659         memcpy(mac, &ee[EEPROM_MAC_ADDRESS], 6);
1660 }
1661
1662 /*
1663  * Either the device driver (i.e. the host) or the firmware can
1664  * load eeprom data into the designated region in SRAM.  If neither
1665  * happens then the FW will shutdown with a fatal error.
1666  *
1667  * In order to signal the FW to load the EEPROM, the EEPROM_LOAD_DISABLE
1668  * bit needs region of shared SRAM needs to be non-zero.
1669  */
1670 static void ipw_eeprom_init_sram(struct ipw_priv *priv)
1671 {
1672         int i;
1673         u16 *eeprom = (u16 *)priv->eeprom;
1674
1675         IPW_DEBUG_TRACE(">>\n");
1676
1677         /* read entire contents of eeprom into private buffer */
1678         for ( i=0; i<128; i++ )
1679                 eeprom[i] = eeprom_read_u16(priv,(u8)i);
1680
1681         /*
1682            If the data looks correct, then copy it to our private
1683            copy.  Otherwise let the firmware know to perform the operation
1684            on it's own
1685         */
1686         if ((priv->eeprom + EEPROM_VERSION) != 0) {
1687                 IPW_DEBUG_INFO("Writing EEPROM data into SRAM\n");
1688
1689                 /* write the eeprom data to sram */
1690                 for( i=0; i<CX2_EEPROM_IMAGE_SIZE; i++ )
1691                         ipw_write8(priv, IPW_EEPROM_DATA + i,
1692                                    priv->eeprom[i]);
1693
1694                 /* Do not load eeprom data on fatal error or suspend */
1695                 ipw_write32(priv, IPW_EEPROM_LOAD_DISABLE, 0);
1696         } else {
1697                 IPW_DEBUG_INFO("Enabling FW initializationg of SRAM\n");
1698
1699                 /* Load eeprom data on fatal error or suspend */
1700                 ipw_write32(priv, IPW_EEPROM_LOAD_DISABLE, 1);
1701         }
1702
1703         IPW_DEBUG_TRACE("<<\n");
1704 }
1705
1706
1707 static inline void ipw_zero_memory(struct ipw_priv *priv, u32 start, u32 count)
1708 {
1709         count >>= 2;
1710         if (!count) return;
1711         _ipw_write32(priv, CX2_AUTOINC_ADDR, start);
1712         while (count--)
1713                 _ipw_write32(priv, CX2_AUTOINC_DATA, 0);
1714 }
1715
1716 static inline void ipw_fw_dma_reset_command_blocks(struct ipw_priv *priv)
1717 {
1718         ipw_zero_memory(priv, CX2_SHARED_SRAM_DMA_CONTROL,
1719                         CB_NUMBER_OF_ELEMENTS_SMALL *
1720                         sizeof(struct command_block));
1721 }
1722
1723 static int ipw_fw_dma_enable(struct ipw_priv *priv)
1724 { /* start dma engine but no transfers yet*/
1725
1726         IPW_DEBUG_FW(">> : \n");
1727
1728         /* Start the dma */
1729         ipw_fw_dma_reset_command_blocks(priv);
1730
1731         /* Write CB base address */
1732         ipw_write_reg32(priv, CX2_DMA_I_CB_BASE, CX2_SHARED_SRAM_DMA_CONTROL);
1733
1734         IPW_DEBUG_FW("<< : \n");
1735         return 0;
1736 }
1737
1738 static void ipw_fw_dma_abort(struct ipw_priv *priv)
1739 {
1740         u32 control = 0;
1741
1742         IPW_DEBUG_FW(">> :\n");
1743
1744         //set the Stop and Abort bit
1745         control = DMA_CONTROL_SMALL_CB_CONST_VALUE | DMA_CB_STOP_AND_ABORT;
1746         ipw_write_reg32(priv, CX2_DMA_I_DMA_CONTROL, control);
1747         priv->sram_desc.last_cb_index = 0;
1748
1749         IPW_DEBUG_FW("<< \n");
1750 }
1751
1752 static int ipw_fw_dma_write_command_block(struct ipw_priv *priv, int index, struct command_block *cb)
1753 {
1754         u32 address = CX2_SHARED_SRAM_DMA_CONTROL + (sizeof(struct command_block) * index);
1755         IPW_DEBUG_FW(">> :\n");
1756
1757         ipw_write_indirect(priv, address, (u8*)cb, (int)sizeof(struct command_block));
1758
1759         IPW_DEBUG_FW("<< :\n");
1760         return 0;
1761
1762 }
1763
1764 static int ipw_fw_dma_kick(struct ipw_priv *priv)
1765 {
1766         u32 control = 0;
1767         u32 index=0;
1768
1769         IPW_DEBUG_FW(">> :\n");
1770
1771         for (index = 0; index < priv->sram_desc.last_cb_index; index++)
1772                 ipw_fw_dma_write_command_block(priv, index, &priv->sram_desc.cb_list[index]);
1773
1774         /* Enable the DMA in the CSR register */
1775         ipw_clear_bit(priv, CX2_RESET_REG,CX2_RESET_REG_MASTER_DISABLED | CX2_RESET_REG_STOP_MASTER);
1776
1777         /* Set the Start bit. */
1778         control = DMA_CONTROL_SMALL_CB_CONST_VALUE | DMA_CB_START;
1779         ipw_write_reg32(priv, CX2_DMA_I_DMA_CONTROL, control);
1780
1781         IPW_DEBUG_FW("<< :\n");
1782         return 0;
1783 }
1784
1785 static void ipw_fw_dma_dump_command_block(struct ipw_priv *priv)
1786 {
1787         u32 address;
1788         u32 register_value=0;
1789         u32 cb_fields_address=0;
1790
1791         IPW_DEBUG_FW(">> :\n");
1792         address = ipw_read_reg32(priv,CX2_DMA_I_CURRENT_CB);
1793         IPW_DEBUG_FW_INFO("Current CB is 0x%x \n",address);
1794
1795         /* Read the DMA Controlor register */
1796         register_value = ipw_read_reg32(priv, CX2_DMA_I_DMA_CONTROL);
1797         IPW_DEBUG_FW_INFO("CX2_DMA_I_DMA_CONTROL is 0x%x \n",register_value);
1798
1799         /* Print the CB values*/
1800         cb_fields_address = address;
1801         register_value = ipw_read_reg32(priv, cb_fields_address);
1802         IPW_DEBUG_FW_INFO("Current CB ControlField is 0x%x \n",register_value);
1803
1804         cb_fields_address += sizeof(u32);
1805         register_value = ipw_read_reg32(priv, cb_fields_address);
1806         IPW_DEBUG_FW_INFO("Current CB Source Field is 0x%x \n",register_value);
1807
1808         cb_fields_address += sizeof(u32);
1809         register_value = ipw_read_reg32(priv, cb_fields_address);
1810         IPW_DEBUG_FW_INFO("Current CB Destination Field is 0x%x \n",
1811                           register_value);
1812
1813         cb_fields_address += sizeof(u32);
1814         register_value = ipw_read_reg32(priv, cb_fields_address);
1815         IPW_DEBUG_FW_INFO("Current CB Status Field is 0x%x \n",register_value);
1816
1817         IPW_DEBUG_FW(">> :\n");
1818 }
1819
1820 static int ipw_fw_dma_command_block_index(struct ipw_priv *priv)
1821 {
1822         u32 current_cb_address = 0;
1823         u32 current_cb_index = 0;
1824
1825         IPW_DEBUG_FW("<< :\n");
1826         current_cb_address= ipw_read_reg32(priv, CX2_DMA_I_CURRENT_CB);
1827
1828         current_cb_index = (current_cb_address - CX2_SHARED_SRAM_DMA_CONTROL )/
1829                 sizeof (struct command_block);
1830
1831         IPW_DEBUG_FW_INFO("Current CB index 0x%x address = 0x%X \n",
1832                           current_cb_index, current_cb_address );
1833
1834         IPW_DEBUG_FW(">> :\n");
1835         return current_cb_index;
1836
1837 }
1838
1839 static int ipw_fw_dma_add_command_block(struct ipw_priv *priv,
1840                                         u32 src_address,
1841                                         u32 dest_address,
1842                                         u32 length,
1843                                         int interrupt_enabled,
1844                                         int is_last)
1845 {
1846
1847         u32 control = CB_VALID | CB_SRC_LE | CB_DEST_LE | CB_SRC_AUTOINC |
1848                 CB_SRC_IO_GATED | CB_DEST_AUTOINC | CB_SRC_SIZE_LONG |
1849                 CB_DEST_SIZE_LONG;
1850         struct command_block *cb;
1851         u32 last_cb_element=0;
1852
1853         IPW_DEBUG_FW_INFO("src_address=0x%x dest_address=0x%x length=0x%x\n",
1854                           src_address, dest_address, length);
1855
1856         if (priv->sram_desc.last_cb_index >= CB_NUMBER_OF_ELEMENTS_SMALL)
1857                 return -1;
1858
1859         last_cb_element = priv->sram_desc.last_cb_index;
1860         cb = &priv->sram_desc.cb_list[last_cb_element];
1861         priv->sram_desc.last_cb_index++;
1862
1863         /* Calculate the new CB control word */
1864         if (interrupt_enabled )
1865                 control |= CB_INT_ENABLED;
1866
1867         if (is_last)
1868                 control |= CB_LAST_VALID;
1869
1870         control |= length;
1871
1872         /* Calculate the CB Element's checksum value */
1873         cb->status = control ^src_address ^dest_address;
1874
1875         /* Copy the Source and Destination addresses */
1876         cb->dest_addr = dest_address;
1877         cb->source_addr = src_address;
1878
1879         /* Copy the Control Word last */
1880         cb->control = control;
1881
1882         return 0;
1883 }
1884
1885 static int ipw_fw_dma_add_buffer(struct ipw_priv *priv,
1886                                  u32 src_phys,
1887                                  u32 dest_address,
1888                                  u32 length)
1889 {
1890         u32 bytes_left = length;
1891         u32 src_offset=0;
1892         u32 dest_offset=0;
1893         int status = 0;
1894         IPW_DEBUG_FW(">> \n");
1895         IPW_DEBUG_FW_INFO("src_phys=0x%x dest_address=0x%x length=0x%x\n",
1896                           src_phys, dest_address, length);
1897         while (bytes_left > CB_MAX_LENGTH) {
1898                 status = ipw_fw_dma_add_command_block( priv,
1899                                                        src_phys + src_offset,
1900                                                        dest_address + dest_offset,
1901                                                        CB_MAX_LENGTH, 0, 0);
1902                 if (status) {
1903                         IPW_DEBUG_FW_INFO(": Failed\n");
1904                         return -1;
1905                 } else
1906                         IPW_DEBUG_FW_INFO(": Added new cb\n");
1907
1908                 src_offset += CB_MAX_LENGTH;
1909                 dest_offset += CB_MAX_LENGTH;
1910                 bytes_left -= CB_MAX_LENGTH;
1911         }
1912
1913         /* add the buffer tail */
1914         if (bytes_left > 0) {
1915                 status = ipw_fw_dma_add_command_block(
1916                         priv, src_phys + src_offset,
1917                         dest_address + dest_offset,
1918                         bytes_left, 0, 0);
1919                 if (status) {
1920                         IPW_DEBUG_FW_INFO(": Failed on the buffer tail\n");
1921                         return -1;
1922                 } else
1923                         IPW_DEBUG_FW_INFO(": Adding new cb - the buffer tail\n");
1924         }
1925
1926
1927         IPW_DEBUG_FW("<< \n");
1928         return 0;
1929 }
1930
1931 static int ipw_fw_dma_wait(struct ipw_priv *priv)
1932 {
1933         u32 current_index = 0;
1934         u32 watchdog = 0;
1935
1936         IPW_DEBUG_FW(">> : \n");
1937
1938         current_index = ipw_fw_dma_command_block_index(priv);
1939         IPW_DEBUG_FW_INFO("sram_desc.last_cb_index:0x%8X\n",
1940                           (int) priv->sram_desc.last_cb_index);
1941
1942         while (current_index < priv->sram_desc.last_cb_index) {
1943                 udelay(50);
1944                 current_index = ipw_fw_dma_command_block_index(priv);
1945
1946                 watchdog++;
1947
1948                 if (watchdog > 400) {
1949                         IPW_DEBUG_FW_INFO("Timeout\n");
1950                         ipw_fw_dma_dump_command_block(priv);
1951                         ipw_fw_dma_abort(priv);
1952                         return -1;
1953                 }
1954         }
1955
1956         ipw_fw_dma_abort(priv);
1957
1958         /*Disable the DMA in the CSR register*/
1959         ipw_set_bit(priv, CX2_RESET_REG,
1960                     CX2_RESET_REG_MASTER_DISABLED | CX2_RESET_REG_STOP_MASTER);
1961
1962         IPW_DEBUG_FW("<< dmaWaitSync \n");
1963         return 0;
1964 }
1965
1966 static void ipw_remove_current_network(struct ipw_priv *priv)
1967 {
1968         struct list_head *element, *safe;
1969         struct ieee80211_network *network = NULL;
1970         list_for_each_safe(element, safe, &priv->ieee->network_list) {
1971                 network = list_entry(element, struct ieee80211_network, list);
1972                 if (!memcmp(network->bssid, priv->bssid, ETH_ALEN)) {
1973                         list_del(element);
1974                         list_add_tail(&network->list,
1975                                       &priv->ieee->network_free_list);
1976                 }
1977         }
1978 }
1979
1980 /**
1981  * Check that card is still alive.
1982  * Reads debug register from domain0.
1983  * If card is present, pre-defined value should
1984  * be found there.
1985  *
1986  * @param priv
1987  * @return 1 if card is present, 0 otherwise
1988  */
1989 static inline int ipw_alive(struct ipw_priv *priv)
1990 {
1991         return ipw_read32(priv, 0x90) == 0xd55555d5;
1992 }
1993
1994 static inline int ipw_poll_bit(struct ipw_priv *priv, u32 addr, u32 mask,
1995                                int timeout)
1996 {
1997         int i = 0;
1998
1999         do {
2000                 if ((ipw_read32(priv, addr) & mask) == mask)
2001                         return i;
2002                 mdelay(10);
2003                 i += 10;
2004         } while (i < timeout);
2005
2006         return -ETIME;
2007 }
2008
2009 /* These functions load the firmware and micro code for the operation of
2010  * the ipw hardware.  It assumes the buffer has all the bits for the
2011  * image and the caller is handling the memory allocation and clean up.
2012  */
2013
2014
2015 static int ipw_stop_master(struct ipw_priv * priv)
2016 {
2017         int rc;
2018
2019         IPW_DEBUG_TRACE(">> \n");
2020         /* stop master. typical delay - 0 */
2021         ipw_set_bit(priv, CX2_RESET_REG, CX2_RESET_REG_STOP_MASTER);
2022
2023         rc = ipw_poll_bit(priv, CX2_RESET_REG,
2024                           CX2_RESET_REG_MASTER_DISABLED, 100);
2025         if (rc < 0) {
2026                 IPW_ERROR("stop master failed in 10ms\n");
2027                 return -1;
2028         }
2029
2030         IPW_DEBUG_INFO("stop master %dms\n", rc);
2031
2032         return rc;
2033 }
2034
2035 static void ipw_arc_release(struct ipw_priv *priv)
2036 {
2037         IPW_DEBUG_TRACE(">> \n");
2038         mdelay(5);
2039
2040         ipw_clear_bit(priv, CX2_RESET_REG, CBD_RESET_REG_PRINCETON_RESET);
2041
2042         /* no one knows timing, for safety add some delay */
2043         mdelay(5);
2044 }
2045
2046 struct fw_header {
2047         u32 version;
2048         u32 mode;
2049 };
2050
2051 struct fw_chunk {
2052         u32 address;
2053         u32 length;
2054 };
2055
2056 #define IPW_FW_MAJOR_VERSION 2
2057 #define IPW_FW_MINOR_VERSION 2
2058
2059 #define IPW_FW_MINOR(x) ((x & 0xff) >> 8)
2060 #define IPW_FW_MAJOR(x) (x & 0xff)
2061
2062 #define IPW_FW_VERSION ((IPW_FW_MINOR_VERSION << 8) | \
2063                          IPW_FW_MAJOR_VERSION)
2064
2065 #define IPW_FW_PREFIX "ipw-" __stringify(IPW_FW_MAJOR_VERSION) \
2066 "." __stringify(IPW_FW_MINOR_VERSION) "-"
2067
2068 #if IPW_FW_MAJOR_VERSION >= 2 && IPW_FW_MINOR_VERSION > 0
2069 #define IPW_FW_NAME(x) IPW_FW_PREFIX "" x ".fw"
2070 #else
2071 #define IPW_FW_NAME(x) "ipw2200_" x ".fw"
2072 #endif
2073
2074 static int ipw_load_ucode(struct ipw_priv *priv, u8 * data,
2075                           size_t len)
2076 {
2077         int rc = 0, i, addr;
2078         u8 cr = 0;
2079         u16 *image;
2080
2081         image = (u16 *)data;
2082
2083         IPW_DEBUG_TRACE(">> \n");
2084
2085         rc = ipw_stop_master(priv);
2086
2087         if (rc < 0)
2088                 return rc;
2089
2090 //      spin_lock_irqsave(&priv->lock, flags);
2091
2092         for (addr = CX2_SHARED_LOWER_BOUND;
2093              addr < CX2_REGISTER_DOMAIN1_END; addr += 4) {
2094                 ipw_write32(priv, addr, 0);
2095         }
2096
2097         /* no ucode (yet) */
2098         memset(&priv->dino_alive, 0, sizeof(priv->dino_alive));
2099         /* destroy DMA queues */
2100         /* reset sequence */
2101
2102         ipw_write_reg32(priv, CX2_MEM_HALT_AND_RESET ,CX2_BIT_HALT_RESET_ON);
2103         ipw_arc_release(priv);
2104         ipw_write_reg32(priv, CX2_MEM_HALT_AND_RESET, CX2_BIT_HALT_RESET_OFF);
2105         mdelay(1);
2106
2107         /* reset PHY */
2108         ipw_write_reg32(priv, CX2_INTERNAL_CMD_EVENT, CX2_BASEBAND_POWER_DOWN);
2109         mdelay(1);
2110
2111         ipw_write_reg32(priv, CX2_INTERNAL_CMD_EVENT, 0);
2112         mdelay(1);
2113
2114         /* enable ucode store */
2115         ipw_write_reg8(priv, DINO_CONTROL_REG, 0x0);
2116         ipw_write_reg8(priv, DINO_CONTROL_REG, DINO_ENABLE_CS);
2117         mdelay(1);
2118
2119         /* write ucode */
2120         /**
2121          * @bug
2122          * Do NOT set indirect address register once and then
2123          * store data to indirect data register in the loop.
2124          * It seems very reasonable, but in this case DINO do not
2125          * accept ucode. It is essential to set address each time.
2126          */
2127         /* load new ipw uCode */
2128         for (i = 0; i < len / 2; i++)
2129                 ipw_write_reg16(priv, CX2_BASEBAND_CONTROL_STORE, image[i]);
2130
2131
2132         /* enable DINO */
2133         ipw_write_reg8(priv, CX2_BASEBAND_CONTROL_STATUS, 0);
2134         ipw_write_reg8(priv, CX2_BASEBAND_CONTROL_STATUS,
2135                        DINO_ENABLE_SYSTEM );
2136
2137         /* this is where the igx / win driver deveates from the VAP driver.*/
2138
2139         /* wait for alive response */
2140         for (i = 0; i < 100; i++) {
2141                 /* poll for incoming data */
2142                 cr = ipw_read_reg8(priv, CX2_BASEBAND_CONTROL_STATUS);
2143                 if (cr & DINO_RXFIFO_DATA)
2144                         break;
2145                 mdelay(1);
2146         }
2147
2148         if (cr & DINO_RXFIFO_DATA) {
2149                 /* alive_command_responce size is NOT multiple of 4 */
2150                 u32 response_buffer[(sizeof(priv->dino_alive) + 3) / 4];
2151
2152                 for (i = 0; i < ARRAY_SIZE(response_buffer); i++)
2153                         response_buffer[i] =
2154                                 ipw_read_reg32(priv,
2155                                                CX2_BASEBAND_RX_FIFO_READ);
2156                 memcpy(&priv->dino_alive, response_buffer,
2157                        sizeof(priv->dino_alive));
2158                 if (priv->dino_alive.alive_command == 1
2159                     && priv->dino_alive.ucode_valid == 1) {
2160                         rc = 0;
2161                         IPW_DEBUG_INFO(
2162                                 "Microcode OK, rev. %d (0x%x) dev. %d (0x%x) "
2163                                 "of %02d/%02d/%02d %02d:%02d\n",
2164                                 priv->dino_alive.software_revision,
2165                                 priv->dino_alive.software_revision,
2166                                 priv->dino_alive.device_identifier,
2167                                 priv->dino_alive.device_identifier,
2168                                 priv->dino_alive.time_stamp[0],
2169                                 priv->dino_alive.time_stamp[1],
2170                                 priv->dino_alive.time_stamp[2],
2171                                 priv->dino_alive.time_stamp[3],
2172                                 priv->dino_alive.time_stamp[4]);
2173                 } else {
2174                         IPW_DEBUG_INFO("Microcode is not alive\n");
2175                         rc = -EINVAL;
2176                 }
2177         } else {
2178                 IPW_DEBUG_INFO("No alive response from DINO\n");
2179                 rc = -ETIME;
2180         }
2181
2182         /* disable DINO, otherwise for some reason
2183            firmware have problem getting alive resp. */
2184         ipw_write_reg8(priv, CX2_BASEBAND_CONTROL_STATUS, 0);
2185
2186 //      spin_unlock_irqrestore(&priv->lock, flags);
2187
2188         return rc;
2189 }
2190
2191 static int ipw_load_firmware(struct ipw_priv *priv, u8 * data,
2192                              size_t len)
2193 {
2194         int rc = -1;
2195         int offset = 0;
2196         struct fw_chunk *chunk;
2197         dma_addr_t shared_phys;
2198         u8 *shared_virt;
2199
2200         IPW_DEBUG_TRACE("<< : \n");
2201         shared_virt = pci_alloc_consistent(priv->pci_dev, len, &shared_phys);
2202
2203         if (!shared_virt)
2204                 return -ENOMEM;
2205
2206         memmove(shared_virt, data, len);
2207
2208         /* Start the Dma */
2209         rc = ipw_fw_dma_enable(priv);
2210
2211         if (priv->sram_desc.last_cb_index > 0) {
2212                 /* the DMA is already ready this would be a bug. */
2213                 BUG();
2214                 goto out;
2215         }
2216
2217         do {
2218                 chunk = (struct fw_chunk *)(data + offset);
2219                 offset += sizeof(struct fw_chunk);
2220                 /* build DMA packet and queue up for sending */
2221                 /* dma to chunk->address, the chunk->length bytes from data +
2222                  * offeset*/
2223                 /* Dma loading */
2224                 rc = ipw_fw_dma_add_buffer(priv, shared_phys + offset,
2225                                            chunk->address, chunk->length);
2226                 if (rc) {
2227                         IPW_DEBUG_INFO("dmaAddBuffer Failed\n");
2228                         goto out;
2229                 }
2230
2231                 offset += chunk->length;
2232         } while (offset < len);
2233
2234         /* Run the DMA and wait for the answer*/
2235         rc = ipw_fw_dma_kick(priv);
2236         if (rc) {
2237                 IPW_ERROR("dmaKick Failed\n");
2238                 goto out;
2239         }
2240
2241         rc = ipw_fw_dma_wait(priv);
2242         if (rc) {
2243                 IPW_ERROR("dmaWaitSync Failed\n");
2244                 goto out;
2245         }
2246  out:
2247         pci_free_consistent( priv->pci_dev, len, shared_virt, shared_phys);
2248         return rc;
2249 }
2250
2251 /* stop nic */
2252 static int ipw_stop_nic(struct ipw_priv *priv)
2253 {
2254         int rc = 0;
2255
2256         /* stop*/
2257         ipw_write32(priv, CX2_RESET_REG, CX2_RESET_REG_STOP_MASTER);
2258
2259         rc = ipw_poll_bit(priv, CX2_RESET_REG,
2260                           CX2_RESET_REG_MASTER_DISABLED, 500);
2261         if (rc < 0) {
2262                 IPW_ERROR("wait for reg master disabled failed\n");
2263                 return rc;
2264         }
2265
2266         ipw_set_bit(priv, CX2_RESET_REG, CBD_RESET_REG_PRINCETON_RESET);
2267
2268         return rc;
2269 }
2270
2271 static void ipw_start_nic(struct ipw_priv *priv)
2272 {
2273         IPW_DEBUG_TRACE(">>\n");
2274
2275         /* prvHwStartNic  release ARC*/
2276         ipw_clear_bit(priv, CX2_RESET_REG,
2277                       CX2_RESET_REG_MASTER_DISABLED |
2278                       CX2_RESET_REG_STOP_MASTER |
2279                       CBD_RESET_REG_PRINCETON_RESET);
2280
2281         /* enable power management */
2282         ipw_set_bit(priv, CX2_GP_CNTRL_RW, CX2_GP_CNTRL_BIT_HOST_ALLOWS_STANDBY);
2283
2284         IPW_DEBUG_TRACE("<<\n");
2285 }
2286
2287 static int ipw_init_nic(struct ipw_priv *priv)
2288 {
2289         int rc;
2290
2291         IPW_DEBUG_TRACE(">>\n");
2292         /* reset */
2293         /*prvHwInitNic */
2294         /* set "initialization complete" bit to move adapter to D0 state */
2295         ipw_set_bit(priv, CX2_GP_CNTRL_RW, CX2_GP_CNTRL_BIT_INIT_DONE);
2296
2297         /* low-level PLL activation */
2298         ipw_write32(priv, CX2_READ_INT_REGISTER,  CX2_BIT_INT_HOST_SRAM_READ_INT_REGISTER);
2299
2300         /* wait for clock stabilization */
2301         rc = ipw_poll_bit(priv, CX2_GP_CNTRL_RW,
2302                           CX2_GP_CNTRL_BIT_CLOCK_READY, 250);
2303         if (rc < 0 )
2304                 IPW_DEBUG_INFO("FAILED wait for clock stablization\n");
2305
2306         /* assert SW reset */
2307         ipw_set_bit(priv, CX2_RESET_REG, CX2_RESET_REG_SW_RESET);
2308
2309         udelay(10);
2310
2311         /* set "initialization complete" bit to move adapter to D0 state */
2312         ipw_set_bit(priv, CX2_GP_CNTRL_RW, CX2_GP_CNTRL_BIT_INIT_DONE);
2313
2314         IPW_DEBUG_TRACE(">>\n");
2315         return 0;
2316 }
2317
2318
2319 /* Call this function from process context, it will sleep in request_firmware.
2320  * Probe is an ok place to call this from.
2321  */
2322 static int ipw_reset_nic(struct ipw_priv *priv)
2323 {
2324         int rc = 0;
2325
2326         IPW_DEBUG_TRACE(">>\n");
2327
2328         rc = ipw_init_nic(priv);
2329
2330         /* Clear the 'host command active' bit... */
2331         priv->status &= ~STATUS_HCMD_ACTIVE;
2332         wake_up_interruptible(&priv->wait_command_queue);
2333
2334         IPW_DEBUG_TRACE("<<\n");
2335         return rc;
2336 }
2337
2338 static int ipw_get_fw(struct ipw_priv *priv,
2339                       const struct firmware **fw, const char *name)
2340 {
2341         struct fw_header *header;
2342         int rc;
2343
2344         /* ask firmware_class module to get the boot firmware off disk */
2345         rc = request_firmware(fw, name, &priv->pci_dev->dev);
2346         if (rc < 0) {
2347                 IPW_ERROR("%s load failed: Reason %d\n", name, rc);
2348                 return rc;
2349         }
2350
2351         header = (struct fw_header *)(*fw)->data;
2352         if (IPW_FW_MAJOR(header->version) != IPW_FW_MAJOR_VERSION) {
2353                 IPW_ERROR("'%s' firmware version not compatible (%d != %d)\n",
2354                           name,
2355                           IPW_FW_MAJOR(header->version), IPW_FW_MAJOR_VERSION);
2356                 return -EINVAL;
2357         }
2358
2359         IPW_DEBUG_INFO("Loading firmware '%s' file v%d.%d (%zd bytes)\n",
2360                        name,
2361                        IPW_FW_MAJOR(header->version),
2362                        IPW_FW_MINOR(header->version),
2363                        (*fw)->size - sizeof(struct fw_header));
2364         return 0;
2365 }
2366
2367 #define CX2_RX_BUF_SIZE (3000)
2368
2369 static inline void ipw_rx_queue_reset(struct ipw_priv *priv,
2370                                       struct ipw_rx_queue *rxq)
2371 {
2372         unsigned long flags;
2373         int i;
2374
2375         spin_lock_irqsave(&rxq->lock, flags);
2376
2377         INIT_LIST_HEAD(&rxq->rx_free);
2378         INIT_LIST_HEAD(&rxq->rx_used);
2379
2380         /* Fill the rx_used queue with _all_ of the Rx buffers */
2381         for (i = 0; i < RX_FREE_BUFFERS + RX_QUEUE_SIZE; i++) {
2382                 /* In the reset function, these buffers may have been allocated
2383                  * to an SKB, so we need to unmap and free potential storage */
2384                 if (rxq->pool[i].skb != NULL) {
2385                         pci_unmap_single(priv->pci_dev, rxq->pool[i].dma_addr,
2386                                          CX2_RX_BUF_SIZE,
2387                                          PCI_DMA_FROMDEVICE);
2388                         dev_kfree_skb(rxq->pool[i].skb);
2389                 }
2390                 list_add_tail(&rxq->pool[i].list, &rxq->rx_used);
2391         }
2392
2393         /* Set us so that we have processed and used all buffers, but have
2394          * not restocked the Rx queue with fresh buffers */
2395         rxq->read = rxq->write = 0;
2396         rxq->processed = RX_QUEUE_SIZE - 1;
2397         rxq->free_count = 0;
2398         spin_unlock_irqrestore(&rxq->lock, flags);
2399 }
2400
2401 #ifdef CONFIG_PM
2402 static int fw_loaded = 0;
2403 static const struct firmware *bootfw = NULL;
2404 static const struct firmware *firmware = NULL;
2405 static const struct firmware *ucode = NULL;
2406 #endif
2407
2408 static int ipw_load(struct ipw_priv *priv)
2409 {
2410 #ifndef CONFIG_PM
2411         const struct firmware *bootfw = NULL;
2412         const struct firmware *firmware = NULL;
2413         const struct firmware *ucode = NULL;
2414 #endif
2415         int rc = 0, retries = 3;
2416
2417 #ifdef CONFIG_PM
2418         if (!fw_loaded) {
2419 #endif
2420                 rc = ipw_get_fw(priv, &bootfw, IPW_FW_NAME("boot"));
2421                 if (rc)
2422                         goto error;
2423
2424                 switch (priv->ieee->iw_mode) {
2425                 case IW_MODE_ADHOC:
2426                         rc = ipw_get_fw(priv, &ucode,
2427                                         IPW_FW_NAME("ibss_ucode"));
2428                         if (rc)
2429                                 goto error;
2430
2431                         rc = ipw_get_fw(priv, &firmware, IPW_FW_NAME("ibss"));
2432                         break;
2433
2434 #ifdef CONFIG_IPW_PROMISC
2435                 case IW_MODE_MONITOR:
2436                         rc = ipw_get_fw(priv, &ucode,
2437                                         IPW_FW_NAME("ibss_ucode"));
2438                         if (rc)
2439                                 goto error;
2440
2441                         rc = ipw_get_fw(priv, &firmware, IPW_FW_NAME("sniffer"));
2442                         break;
2443 #endif
2444                 case IW_MODE_INFRA:
2445                         rc = ipw_get_fw(priv, &ucode,
2446                                         IPW_FW_NAME("bss_ucode"));
2447                         if (rc)
2448                                 goto error;
2449
2450                         rc = ipw_get_fw(priv, &firmware, IPW_FW_NAME("bss"));
2451                         break;
2452
2453                 default:
2454                         rc = -EINVAL;
2455                 }
2456
2457                 if (rc)
2458                         goto error;
2459
2460 #ifdef CONFIG_PM
2461                 fw_loaded = 1;
2462         }
2463 #endif
2464
2465         if (!priv->rxq)
2466                 priv->rxq = ipw_rx_queue_alloc(priv);
2467         else
2468                 ipw_rx_queue_reset(priv, priv->rxq);
2469         if (!priv->rxq) {
2470                 IPW_ERROR("Unable to initialize Rx queue\n");
2471                 goto error;
2472         }
2473
2474  retry:
2475         /* Ensure interrupts are disabled */
2476         ipw_write32(priv, CX2_INTA_MASK_R, ~CX2_INTA_MASK_ALL);
2477         priv->status &= ~STATUS_INT_ENABLED;
2478
2479         /* ack pending interrupts */
2480         ipw_write32(priv, CX2_INTA_RW, CX2_INTA_MASK_ALL);
2481
2482         ipw_stop_nic(priv);
2483
2484         rc = ipw_reset_nic(priv);
2485         if (rc) {
2486                 IPW_ERROR("Unable to reset NIC\n");
2487                 goto error;
2488         }
2489
2490         ipw_zero_memory(priv, CX2_NIC_SRAM_LOWER_BOUND,
2491                         CX2_NIC_SRAM_UPPER_BOUND - CX2_NIC_SRAM_LOWER_BOUND);
2492
2493         /* DMA the initial boot firmware into the device */
2494         rc = ipw_load_firmware(priv, bootfw->data + sizeof(struct fw_header),
2495                                bootfw->size - sizeof(struct fw_header));
2496         if (rc < 0) {
2497                 IPW_ERROR("Unable to load boot firmware\n");
2498                 goto error;
2499         }
2500
2501         /* kick start the device */
2502         ipw_start_nic(priv);
2503
2504         /* wait for the device to finish it's initial startup sequence */
2505         rc = ipw_poll_bit(priv, CX2_INTA_RW,
2506                           CX2_INTA_BIT_FW_INITIALIZATION_DONE, 500);
2507         if (rc < 0) {
2508                 IPW_ERROR("device failed to boot initial fw image\n");
2509                 goto error;
2510         }
2511         IPW_DEBUG_INFO("initial device response after %dms\n", rc);
2512
2513         /* ack fw init done interrupt */
2514         ipw_write32(priv, CX2_INTA_RW, CX2_INTA_BIT_FW_INITIALIZATION_DONE);
2515
2516         /* DMA the ucode into the device */
2517         rc = ipw_load_ucode(priv, ucode->data + sizeof(struct fw_header),
2518                             ucode->size - sizeof(struct fw_header));
2519         if (rc < 0) {
2520                 IPW_ERROR("Unable to load ucode\n");
2521                 goto error;
2522         }
2523
2524         /* stop nic */
2525         ipw_stop_nic(priv);
2526
2527         /* DMA bss firmware into the device */
2528         rc = ipw_load_firmware(priv, firmware->data +
2529                                sizeof(struct fw_header),
2530                                firmware->size - sizeof(struct fw_header));
2531         if (rc < 0 ) {
2532                 IPW_ERROR("Unable to load firmware\n");
2533                 goto error;
2534         }
2535
2536         ipw_write32(priv, IPW_EEPROM_LOAD_DISABLE, 0);
2537
2538         rc = ipw_queue_reset(priv);
2539         if (rc) {
2540                 IPW_ERROR("Unable to initialize queues\n");
2541                 goto error;
2542         }
2543
2544         /* Ensure interrupts are disabled */
2545         ipw_write32(priv, CX2_INTA_MASK_R, ~CX2_INTA_MASK_ALL);
2546
2547         /* kick start the device */
2548         ipw_start_nic(priv);
2549
2550         if (ipw_read32(priv, CX2_INTA_RW) & CX2_INTA_BIT_PARITY_ERROR) {
2551                 if (retries > 0) {
2552                         IPW_WARNING("Parity error.  Retrying init.\n");
2553                         retries--;
2554                         goto retry;
2555                 }
2556
2557                 IPW_ERROR("TODO: Handle parity error -- schedule restart?\n");
2558                 rc = -EIO;
2559                 goto error;
2560         }
2561
2562         /* wait for the device */
2563         rc = ipw_poll_bit(priv, CX2_INTA_RW,
2564                           CX2_INTA_BIT_FW_INITIALIZATION_DONE, 500);
2565         if (rc < 0) {
2566                 IPW_ERROR("device failed to start after 500ms\n");
2567                 goto error;
2568         }
2569         IPW_DEBUG_INFO("device response after %dms\n", rc);
2570
2571         /* ack fw init done interrupt */
2572         ipw_write32(priv, CX2_INTA_RW, CX2_INTA_BIT_FW_INITIALIZATION_DONE);
2573
2574         /* read eeprom data and initialize the eeprom region of sram */
2575         priv->eeprom_delay = 1;
2576         ipw_eeprom_init_sram(priv);
2577
2578         /* enable interrupts */
2579         ipw_enable_interrupts(priv);
2580
2581         /* Ensure our queue has valid packets */
2582         ipw_rx_queue_replenish(priv);
2583
2584         ipw_write32(priv, CX2_RX_READ_INDEX, priv->rxq->read);
2585
2586         /* ack pending interrupts */
2587         ipw_write32(priv, CX2_INTA_RW, CX2_INTA_MASK_ALL);
2588
2589 #ifndef CONFIG_PM
2590         release_firmware(bootfw);
2591         release_firmware(ucode);
2592         release_firmware(firmware);
2593 #endif
2594         return 0;
2595
2596  error:
2597         if (priv->rxq) {
2598                 ipw_rx_queue_free(priv, priv->rxq);
2599                 priv->rxq = NULL;
2600         }
2601         ipw_tx_queue_free(priv);
2602         if (bootfw)
2603                 release_firmware(bootfw);
2604         if (ucode)
2605                 release_firmware(ucode);
2606         if (firmware)
2607                 release_firmware(firmware);
2608 #ifdef CONFIG_PM
2609         fw_loaded = 0;
2610         bootfw = ucode = firmware = NULL;
2611 #endif
2612
2613         return rc;
2614 }
2615
2616 /**
2617  * DMA services
2618  *
2619  * Theory of operation
2620  *
2621  * A queue is a circular buffers with 'Read' and 'Write' pointers.
2622  * 2 empty entries always kept in the buffer to protect from overflow.
2623  *
2624  * For Tx queue, there are low mark and high mark limits. If, after queuing
2625  * the packet for Tx, free space become < low mark, Tx queue stopped. When
2626  * reclaiming packets (on 'tx done IRQ), if free space become > high mark,
2627  * Tx queue resumed.
2628  *
2629  * The IPW operates with six queues, one receive queue in the device's
2630  * sram, one transmit queue for sending commands to the device firmware,
2631  * and four transmit queues for data.
2632  *
2633  * The four transmit queues allow for performing quality of service (qos)
2634  * transmissions as per the 802.11 protocol.  Currently Linux does not
2635  * provide a mechanism to the user for utilizing prioritized queues, so
2636  * we only utilize the first data transmit queue (queue1).
2637  */
2638
2639 /**
2640  * Driver allocates buffers of this size for Rx
2641  */
2642
2643 static inline int ipw_queue_space(const struct clx2_queue *q)
2644 {
2645         int s = q->last_used - q->first_empty;
2646         if (s <= 0)
2647                 s += q->n_bd;
2648         s -= 2;                 /* keep some reserve to not confuse empty and full situations */
2649         if (s < 0)
2650                 s = 0;
2651         return s;
2652 }
2653
2654 static inline int ipw_queue_inc_wrap(int index, int n_bd)
2655 {
2656         return (++index == n_bd) ? 0 : index;
2657 }
2658
2659 /**
2660  * Initialize common DMA queue structure
2661  *
2662  * @param q                queue to init
2663  * @param count            Number of BD's to allocate. Should be power of 2
2664  * @param read_register    Address for 'read' register
2665  *                         (not offset within BAR, full address)
2666  * @param write_register   Address for 'write' register
2667  *                         (not offset within BAR, full address)
2668  * @param base_register    Address for 'base' register
2669  *                         (not offset within BAR, full address)
2670  * @param size             Address for 'size' register
2671  *                         (not offset within BAR, full address)
2672  */
2673 static void ipw_queue_init(struct ipw_priv *priv, struct clx2_queue *q,
2674                            int count, u32 read, u32 write,
2675                            u32 base, u32 size)
2676 {
2677         q->n_bd = count;
2678
2679         q->low_mark = q->n_bd / 4;
2680         if (q->low_mark < 4)
2681                 q->low_mark = 4;
2682
2683         q->high_mark = q->n_bd / 8;
2684         if (q->high_mark < 2)
2685                 q->high_mark = 2;
2686
2687         q->first_empty = q->last_used = 0;
2688         q->reg_r = read;
2689         q->reg_w = write;
2690
2691         ipw_write32(priv, base, q->dma_addr);
2692         ipw_write32(priv, size, count);
2693         ipw_write32(priv, read, 0);
2694         ipw_write32(priv, write, 0);
2695
2696         _ipw_read32(priv, 0x90);
2697 }
2698
2699 static int ipw_queue_tx_init(struct ipw_priv *priv,
2700                              struct clx2_tx_queue *q,
2701                              int count, u32 read, u32 write,
2702                              u32 base, u32 size)
2703 {
2704         struct pci_dev *dev = priv->pci_dev;
2705
2706         q->txb = kmalloc(sizeof(q->txb[0]) * count, GFP_KERNEL);
2707         if (!q->txb) {
2708                 IPW_ERROR("vmalloc for auxilary BD structures failed\n");
2709                 return -ENOMEM;
2710         }
2711
2712         q->bd = pci_alloc_consistent(dev,sizeof(q->bd[0])*count, &q->q.dma_addr);
2713         if (!q->bd) {
2714                 IPW_ERROR("pci_alloc_consistent(%zd) failed\n",
2715                                 sizeof(q->bd[0]) * count);
2716                 kfree(q->txb);
2717                 q->txb = NULL;
2718                 return -ENOMEM;
2719         }
2720
2721         ipw_queue_init(priv, &q->q, count, read, write, base, size);
2722         return 0;
2723 }
2724
2725 /**
2726  * Free one TFD, those at index [txq->q.last_used].
2727  * Do NOT advance any indexes
2728  *
2729  * @param dev
2730  * @param txq
2731  */
2732 static void ipw_queue_tx_free_tfd(struct ipw_priv *priv,
2733                                   struct clx2_tx_queue *txq)
2734 {
2735         struct tfd_frame *bd = &txq->bd[txq->q.last_used];
2736         struct pci_dev *dev = priv->pci_dev;
2737         int i;
2738
2739         /* classify bd */
2740         if (bd->control_flags.message_type == TX_HOST_COMMAND_TYPE)
2741                 /* nothing to cleanup after for host commands */
2742                 return;
2743
2744         /* sanity check */
2745         if (bd->u.data.num_chunks > NUM_TFD_CHUNKS) {
2746                 IPW_ERROR("Too many chunks: %i\n", bd->u.data.num_chunks);
2747                 /** @todo issue fatal error, it is quite serious situation */
2748                 return;
2749         }
2750
2751         /* unmap chunks if any */
2752         for (i = 0; i < bd->u.data.num_chunks; i++) {
2753                 pci_unmap_single(dev, bd->u.data.chunk_ptr[i],
2754                                  bd->u.data.chunk_len[i], PCI_DMA_TODEVICE);
2755                 if (txq->txb[txq->q.last_used]) {
2756                         ieee80211_txb_free(txq->txb[txq->q.last_used]);
2757                         txq->txb[txq->q.last_used] = NULL;
2758                 }
2759         }
2760 }
2761
2762 /**
2763  * Deallocate DMA queue.
2764  *
2765  * Empty queue by removing and destroying all BD's.
2766  * Free all buffers.
2767  *
2768  * @param dev
2769  * @param q
2770  */
2771 static void ipw_queue_tx_free(struct ipw_priv *priv,
2772                             struct clx2_tx_queue *txq)
2773 {
2774         struct clx2_queue *q = &txq->q;
2775         struct pci_dev *dev = priv->pci_dev;
2776
2777         if (q->n_bd == 0)
2778                 return;
2779
2780         /* first, empty all BD's */
2781         for (; q->first_empty != q->last_used;
2782              q->last_used = ipw_queue_inc_wrap(q->last_used, q->n_bd)) {
2783                 ipw_queue_tx_free_tfd(priv, txq);
2784         }
2785
2786         /* free buffers belonging to queue itself */
2787         pci_free_consistent(dev, sizeof(txq->bd[0])*q->n_bd, txq->bd,
2788                             q->dma_addr);
2789         kfree(txq->txb);
2790
2791         /* 0 fill whole structure */
2792         memset(txq, 0, sizeof(*txq));
2793 }
2794
2795
2796 /**
2797  * Destroy all DMA queues and structures
2798  *
2799  * @param priv
2800  */
2801 static void ipw_tx_queue_free(struct ipw_priv *priv)
2802 {
2803         /* Tx CMD queue */
2804         ipw_queue_tx_free(priv, &priv->txq_cmd);
2805
2806         /* Tx queues */
2807         ipw_queue_tx_free(priv, &priv->txq[0]);
2808         ipw_queue_tx_free(priv, &priv->txq[1]);
2809         ipw_queue_tx_free(priv, &priv->txq[2]);
2810         ipw_queue_tx_free(priv, &priv->txq[3]);
2811 }
2812
2813 static void inline __maybe_wake_tx(struct ipw_priv *priv)
2814 {
2815         if (netif_running(priv->net_dev)) {
2816                 switch (priv->port_type) {
2817                 case DCR_TYPE_MU_BSS:
2818                 case DCR_TYPE_MU_IBSS:
2819                         if (!(priv->status & STATUS_ASSOCIATED)) {
2820                                 return;
2821                         }
2822                 }
2823                 netif_wake_queue(priv->net_dev);
2824         }
2825
2826 }
2827
2828 static inline void ipw_create_bssid(struct ipw_priv *priv, u8 *bssid)
2829 {
2830         /* First 3 bytes are manufacturer */
2831         bssid[0] = priv->mac_addr[0];
2832         bssid[1] = priv->mac_addr[1];
2833         bssid[2] = priv->mac_addr[2];
2834
2835         /* Last bytes are random */
2836         get_random_bytes(&bssid[3], ETH_ALEN-3);
2837
2838         bssid[0] &= 0xfe;       /* clear multicast bit */
2839         bssid[0] |= 0x02;       /* set local assignment bit (IEEE802) */
2840 }
2841
2842 static inline u8 ipw_add_station(struct ipw_priv *priv, u8 *bssid)
2843 {
2844         struct ipw_station_entry entry;
2845         int i;
2846
2847         for (i = 0; i < priv->num_stations; i++) {
2848                 if (!memcmp(priv->stations[i], bssid, ETH_ALEN)) {
2849                         /* Another node is active in network */
2850                         priv->missed_adhoc_beacons = 0;
2851                         if (!(priv->config & CFG_STATIC_CHANNEL))
2852                                 /* when other nodes drop out, we drop out */
2853                                 priv->config &= ~CFG_ADHOC_PERSIST;
2854
2855                         return i;
2856                 }
2857         }
2858
2859         if (i == MAX_STATIONS)
2860                 return IPW_INVALID_STATION;
2861
2862         IPW_DEBUG_SCAN("Adding AdHoc station: " MAC_FMT "\n", MAC_ARG(bssid));
2863
2864         entry.reserved = 0;
2865         entry.support_mode = 0;
2866         memcpy(entry.mac_addr, bssid, ETH_ALEN);
2867         memcpy(priv->stations[i], bssid, ETH_ALEN);
2868         ipw_write_direct(priv, IPW_STATION_TABLE_LOWER + i * sizeof(entry),
2869                          &entry,
2870                          sizeof(entry));
2871         priv->num_stations++;
2872
2873         return i;
2874 }
2875
2876 static inline u8 ipw_find_station(struct ipw_priv *priv, u8 *bssid)
2877 {
2878         int i;
2879
2880         for (i = 0; i < priv->num_stations; i++)
2881                 if (!memcmp(priv->stations[i], bssid, ETH_ALEN))
2882                         return i;
2883
2884         return IPW_INVALID_STATION;
2885 }
2886
2887 static void ipw_send_disassociate(struct ipw_priv *priv, int quiet)
2888 {
2889         int err;
2890
2891         if (!(priv->status & (STATUS_ASSOCIATING | STATUS_ASSOCIATED))) {
2892                 IPW_DEBUG_ASSOC("Disassociating while not associated.\n");
2893                 return;
2894         }
2895
2896         IPW_DEBUG_ASSOC("Disassocation attempt from " MAC_FMT " "
2897                         "on channel %d.\n",
2898                         MAC_ARG(priv->assoc_request.bssid),
2899                         priv->assoc_request.channel);
2900
2901         priv->status &= ~(STATUS_ASSOCIATING | STATUS_ASSOCIATED);
2902         priv->status |= STATUS_DISASSOCIATING;
2903
2904         if (quiet)
2905                 priv->assoc_request.assoc_type = HC_DISASSOC_QUIET;
2906         else
2907                 priv->assoc_request.assoc_type = HC_DISASSOCIATE;
2908         err = ipw_send_associate(priv, &priv->assoc_request);
2909         if (err) {
2910                 IPW_DEBUG_HC("Attempt to send [dis]associate command "
2911                              "failed.\n");
2912                 return;
2913         }
2914
2915 }
2916
2917 static void ipw_disassociate(void *data)
2918 {
2919         ipw_send_disassociate(data, 0);
2920 }
2921
2922 static void notify_wx_assoc_event(struct ipw_priv *priv)
2923 {
2924         union iwreq_data wrqu;
2925         wrqu.ap_addr.sa_family = ARPHRD_ETHER;
2926         if (priv->status & STATUS_ASSOCIATED)
2927                 memcpy(wrqu.ap_addr.sa_data, priv->bssid, ETH_ALEN);
2928         else
2929                 memset(wrqu.ap_addr.sa_data, 0, ETH_ALEN);
2930         wireless_send_event(priv->net_dev, SIOCGIWAP, &wrqu, NULL);
2931 }
2932
2933 struct ipw_status_code {
2934         u16 status;
2935         const char *reason;
2936 };
2937
2938 static const struct ipw_status_code ipw_status_codes[] = {
2939         {0x00, "Successful"},
2940         {0x01, "Unspecified failure"},
2941         {0x0A, "Cannot support all requested capabilities in the "
2942          "Capability information field"},
2943         {0x0B, "Reassociation denied due to inability to confirm that "
2944          "association exists"},
2945         {0x0C, "Association denied due to reason outside the scope of this "
2946          "standard"},
2947         {0x0D, "Responding station does not support the specified authentication "
2948          "algorithm"},
2949         {0x0E, "Received an Authentication frame with authentication sequence "
2950          "transaction sequence number out of expected sequence"},
2951         {0x0F, "Authentication rejected because of challenge failure"},
2952         {0x10, "Authentication rejected due to timeout waiting for next "
2953          "frame in sequence"},
2954         {0x11, "Association denied because AP is unable to handle additional "
2955          "associated stations"},
2956         {0x12, "Association denied due to requesting station not supporting all "
2957          "of the datarates in the BSSBasicServiceSet Parameter"},
2958         {0x13, "Association denied due to requesting station not supporting "
2959          "short preamble operation"},
2960         {0x14, "Association denied due to requesting station not supporting "
2961          "PBCC encoding"},
2962         {0x15, "Association denied due to requesting station not supporting "
2963          "channel agility"},
2964         {0x19, "Association denied due to requesting station not supporting "
2965          "short slot operation"},
2966         {0x1A, "Association denied due to requesting station not supporting "
2967          "DSSS-OFDM operation"},
2968         {0x28, "Invalid Information Element"},
2969         {0x29, "Group Cipher is not valid"},
2970         {0x2A, "Pairwise Cipher is not valid"},
2971         {0x2B, "AKMP is not valid"},
2972         {0x2C, "Unsupported RSN IE version"},
2973         {0x2D, "Invalid RSN IE Capabilities"},
2974         {0x2E, "Cipher suite is rejected per security policy"},
2975 };
2976
2977 #ifdef CONFIG_IPW_DEBUG
2978 static const char *ipw_get_status_code(u16 status)
2979 {
2980         int i;
2981         for (i = 0; i < ARRAY_SIZE(ipw_status_codes); i++)
2982                 if (ipw_status_codes[i].status == status)
2983                         return ipw_status_codes[i].reason;
2984         return "Unknown status value.";
2985 }
2986 #endif
2987
2988 static void inline average_init(struct average *avg)
2989 {
2990         memset(avg, 0, sizeof(*avg));
2991 }
2992
2993 static void inline average_add(struct average *avg, s16 val)
2994 {
2995         avg->sum -= avg->entries[avg->pos];
2996         avg->sum += val;
2997         avg->entries[avg->pos++] = val;
2998         if (unlikely(avg->pos == AVG_ENTRIES)) {
2999                 avg->init = 1;
3000                 avg->pos = 0;
3001         }
3002 }
3003
3004 static s16 inline average_value(struct average *avg)
3005 {
3006         if (!unlikely(avg->init)) {
3007                 if (avg->pos)
3008                         return avg->sum / avg->pos;
3009                 return 0;
3010         }
3011
3012         return avg->sum / AVG_ENTRIES;
3013 }
3014
3015 static void ipw_reset_stats(struct ipw_priv *priv)
3016 {
3017         u32 len = sizeof(u32);
3018
3019         priv->quality = 0;
3020
3021         average_init(&priv->average_missed_beacons);
3022         average_init(&priv->average_rssi);
3023         average_init(&priv->average_noise);
3024
3025         priv->last_rate = 0;
3026         priv->last_missed_beacons = 0;
3027         priv->last_rx_packets = 0;
3028         priv->last_tx_packets = 0;
3029         priv->last_tx_failures = 0;
3030
3031         /* Firmware managed, reset only when NIC is restarted, so we have to
3032          * normalize on the current value */
3033         ipw_get_ordinal(priv, IPW_ORD_STAT_RX_ERR_CRC,
3034                         &priv->last_rx_err, &len);
3035         ipw_get_ordinal(priv, IPW_ORD_STAT_TX_FAILURE,
3036                         &priv->last_tx_failures, &len);
3037
3038         /* Driver managed, reset with each association */
3039         priv->missed_adhoc_beacons = 0;
3040         priv->missed_beacons = 0;
3041         priv->tx_packets = 0;
3042         priv->rx_packets = 0;
3043
3044 }
3045
3046
3047 static inline u32 ipw_get_max_rate(struct ipw_priv *priv)
3048 {
3049         u32 i = 0x80000000;
3050         u32 mask = priv->rates_mask;
3051         /* If currently associated in B mode, restrict the maximum
3052          * rate match to B rates */
3053         if (priv->assoc_request.ieee_mode == IPW_B_MODE)
3054                 mask &= IEEE80211_CCK_RATES_MASK;
3055
3056         /* TODO: Verify that the rate is supported by the current rates
3057          * list. */
3058
3059         while (i && !(mask & i)) i >>= 1;
3060         switch (i) {
3061         case IEEE80211_CCK_RATE_1MB_MASK: return 1000000;
3062         case IEEE80211_CCK_RATE_2MB_MASK: return 2000000;
3063         case IEEE80211_CCK_RATE_5MB_MASK: return 5500000;
3064         case IEEE80211_OFDM_RATE_6MB_MASK: return 6000000;
3065         case IEEE80211_OFDM_RATE_9MB_MASK: return 9000000;
3066         case IEEE80211_CCK_RATE_11MB_MASK: return 11000000;
3067         case IEEE80211_OFDM_RATE_12MB_MASK: return 12000000;
3068         case IEEE80211_OFDM_RATE_18MB_MASK: return 18000000;
3069         case IEEE80211_OFDM_RATE_24MB_MASK: return 24000000;
3070         case IEEE80211_OFDM_RATE_36MB_MASK: return 36000000;
3071         case IEEE80211_OFDM_RATE_48MB_MASK: return 48000000;
3072         case IEEE80211_OFDM_RATE_54MB_MASK: return 54000000;
3073         }
3074
3075         if (priv->ieee->mode == IEEE_B)
3076                 return 11000000;
3077         else
3078                 return 54000000;
3079 }
3080
3081 static u32 ipw_get_current_rate(struct ipw_priv *priv)
3082 {
3083         u32 rate, len = sizeof(rate);
3084         int err;
3085
3086         if (!(priv->status & STATUS_ASSOCIATED))
3087                 return 0;
3088
3089         if (priv->tx_packets > IPW_REAL_RATE_RX_PACKET_THRESHOLD) {
3090                 err = ipw_get_ordinal(priv, IPW_ORD_STAT_TX_CURR_RATE, &rate,
3091                                       &len);
3092                 if (err) {
3093                         IPW_DEBUG_INFO("failed querying ordinals.\n");
3094                         return 0;
3095                 }
3096         } else
3097                 return ipw_get_max_rate(priv);
3098
3099         switch (rate) {
3100         case IPW_TX_RATE_1MB:  return  1000000;
3101         case IPW_TX_RATE_2MB:  return  2000000;
3102         case IPW_TX_RATE_5MB:  return  5500000;
3103         case IPW_TX_RATE_6MB:  return  6000000;
3104         case IPW_TX_RATE_9MB:  return  9000000;
3105         case IPW_TX_RATE_11MB: return 11000000;
3106         case IPW_TX_RATE_12MB: return 12000000;
3107         case IPW_TX_RATE_18MB: return 18000000;
3108         case IPW_TX_RATE_24MB: return 24000000;
3109         case IPW_TX_RATE_36MB: return 36000000;
3110         case IPW_TX_RATE_48MB: return 48000000;
3111         case IPW_TX_RATE_54MB: return 54000000;
3112         }
3113
3114         return 0;
3115 }
3116
3117 #define PERFECT_RSSI (-50)
3118 #define WORST_RSSI   (-85)
3119 #define IPW_STATS_INTERVAL (2 * HZ)
3120 static void ipw_gather_stats(struct ipw_priv *priv)
3121 {
3122         u32 rx_err, rx_err_delta, rx_packets_delta;
3123         u32 tx_failures, tx_failures_delta, tx_packets_delta;
3124         u32 missed_beacons_percent, missed_beacons_delta;
3125         u32 quality = 0;
3126         u32 len = sizeof(u32);
3127         s16 rssi;
3128         u32 beacon_quality, signal_quality, tx_quality, rx_quality,
3129                 rate_quality;
3130
3131         if (!(priv->status & STATUS_ASSOCIATED)) {
3132                 priv->quality = 0;
3133                 return;
3134         }
3135
3136         /* Update the statistics */
3137         ipw_get_ordinal(priv, IPW_ORD_STAT_MISSED_BEACONS,
3138                         &priv->missed_beacons, &len);
3139         missed_beacons_delta = priv->missed_beacons -
3140                 priv->last_missed_beacons;
3141         priv->last_missed_beacons = priv->missed_beacons;
3142         if (priv->assoc_request.beacon_interval) {
3143                 missed_beacons_percent = missed_beacons_delta *
3144                         (HZ * priv->assoc_request.beacon_interval) /
3145                         (IPW_STATS_INTERVAL * 10);
3146         } else {
3147                 missed_beacons_percent = 0;
3148         }
3149         average_add(&priv->average_missed_beacons, missed_beacons_percent);
3150
3151         ipw_get_ordinal(priv, IPW_ORD_STAT_RX_ERR_CRC, &rx_err, &len);
3152         rx_err_delta = rx_err - priv->last_rx_err;
3153         priv->last_rx_err = rx_err;
3154
3155         ipw_get_ordinal(priv, IPW_ORD_STAT_TX_FAILURE, &tx_failures, &len);
3156         tx_failures_delta = tx_failures - priv->last_tx_failures;
3157         priv->last_tx_failures = tx_failures;
3158
3159         rx_packets_delta = priv->rx_packets - priv->last_rx_packets;
3160         priv->last_rx_packets = priv->rx_packets;
3161
3162         tx_packets_delta = priv->tx_packets - priv->last_tx_packets;
3163         priv->last_tx_packets = priv->tx_packets;
3164
3165         /* Calculate quality based on the following:
3166          *
3167          * Missed beacon: 100% = 0, 0% = 70% missed
3168          * Rate: 60% = 1Mbs, 100% = Max
3169          * Rx and Tx errors represent a straight % of total Rx/Tx
3170          * RSSI: 100% = > -50,  0% = < -80
3171          * Rx errors: 100% = 0, 0% = 50% missed
3172          *
3173          * The lowest computed quality is used.
3174          *
3175          */
3176 #define BEACON_THRESHOLD 5
3177         beacon_quality = 100 - missed_beacons_percent;
3178         if (beacon_quality < BEACON_THRESHOLD)
3179                 beacon_quality = 0;
3180         else
3181                 beacon_quality = (beacon_quality - BEACON_THRESHOLD) * 100 /
3182                         (100 - BEACON_THRESHOLD);
3183         IPW_DEBUG_STATS("Missed beacon: %3d%% (%d%%)\n",
3184                         beacon_quality, missed_beacons_percent);
3185
3186         priv->last_rate = ipw_get_current_rate(priv);
3187         rate_quality =  priv->last_rate * 40 / priv->last_rate + 60;
3188         IPW_DEBUG_STATS("Rate quality : %3d%% (%dMbs)\n",
3189                         rate_quality, priv->last_rate / 1000000);
3190
3191         if (rx_packets_delta > 100 &&
3192             rx_packets_delta + rx_err_delta)
3193                 rx_quality = 100 - (rx_err_delta * 100) /
3194                         (rx_packets_delta + rx_err_delta);
3195         else
3196                 rx_quality = 100;
3197         IPW_DEBUG_STATS("Rx quality   : %3d%% (%u errors, %u packets)\n",
3198                         rx_quality, rx_err_delta, rx_packets_delta);
3199
3200         if (tx_packets_delta > 100 &&
3201             tx_packets_delta + tx_failures_delta)
3202                 tx_quality = 100 - (tx_failures_delta * 100) /
3203                         (tx_packets_delta + tx_failures_delta);
3204         else
3205                 tx_quality = 100;
3206         IPW_DEBUG_STATS("Tx quality   : %3d%% (%u errors, %u packets)\n",
3207                         tx_quality, tx_failures_delta, tx_packets_delta);
3208
3209         rssi = average_value(&priv->average_rssi);
3210         if (rssi > PERFECT_RSSI)
3211                 signal_quality = 100;
3212         else if (rssi < WORST_RSSI)
3213                 signal_quality = 0;
3214         else
3215                 signal_quality = (rssi - WORST_RSSI) * 100 /
3216                         (PERFECT_RSSI - WORST_RSSI);
3217         IPW_DEBUG_STATS("Signal level : %3d%% (%d dBm)\n",
3218                         signal_quality, rssi);
3219
3220         quality = min(beacon_quality,
3221                       min(rate_quality,
3222                           min(tx_quality, min(rx_quality, signal_quality))));
3223         if (quality == beacon_quality)
3224                 IPW_DEBUG_STATS(
3225                         "Quality (%d%%): Clamped to missed beacons.\n",
3226                         quality);
3227         if (quality == rate_quality)
3228                 IPW_DEBUG_STATS(
3229                         "Quality (%d%%): Clamped to rate quality.\n",
3230                         quality);
3231         if (quality == tx_quality)
3232                 IPW_DEBUG_STATS(
3233                         "Quality (%d%%): Clamped to Tx quality.\n",
3234                         quality);
3235         if (quality == rx_quality)
3236                 IPW_DEBUG_STATS(
3237                         "Quality (%d%%): Clamped to Rx quality.\n",
3238                         quality);
3239         if (quality == signal_quality)
3240                 IPW_DEBUG_STATS(
3241                         "Quality (%d%%): Clamped to signal quality.\n",
3242                         quality);
3243
3244         priv->quality = quality;
3245
3246         queue_delayed_work(priv->workqueue, &priv->gather_stats,
3247                            IPW_STATS_INTERVAL);
3248 }
3249
3250 /**
3251  * Handle host notification packet.
3252  * Called from interrupt routine
3253  */
3254 static inline void ipw_rx_notification(struct ipw_priv* priv,
3255                                        struct ipw_rx_notification *notif)
3256 {
3257         IPW_DEBUG_NOTIF("type = %i (%d bytes)\n",
3258                         notif->subtype, notif->size);
3259
3260         switch (notif->subtype) {
3261         case HOST_NOTIFICATION_STATUS_ASSOCIATED: {
3262                 struct notif_association *assoc = &notif->u.assoc;
3263
3264                 switch (assoc->state) {
3265                 case CMAS_ASSOCIATED: {
3266                         IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE | IPW_DL_ASSOC,
3267                                   "associated: '%s' " MAC_FMT " \n",
3268                                   escape_essid(priv->essid, priv->essid_len),
3269                                   MAC_ARG(priv->bssid));
3270
3271                         switch (priv->ieee->iw_mode) {
3272                         case IW_MODE_INFRA:
3273                                 memcpy(priv->ieee->bssid, priv->bssid,
3274                                        ETH_ALEN);
3275                                 break;
3276
3277                         case IW_MODE_ADHOC:
3278                                 memcpy(priv->ieee->bssid, priv->bssid,
3279                                        ETH_ALEN);
3280
3281                                 /* clear out the station table */
3282                                 priv->num_stations = 0;
3283
3284                                 IPW_DEBUG_ASSOC("queueing adhoc check\n");
3285                                 queue_delayed_work(priv->workqueue,
3286                                                    &priv->adhoc_check,
3287                                                    priv->assoc_request.beacon_interval);
3288                                 break;
3289                         }
3290
3291                         priv->status &= ~STATUS_ASSOCIATING;
3292                         priv->status |= STATUS_ASSOCIATED;
3293
3294                         netif_carrier_on(priv->net_dev);
3295                         if (netif_queue_stopped(priv->net_dev)) {
3296                                 IPW_DEBUG_NOTIF("waking queue\n");
3297                                 netif_wake_queue(priv->net_dev);
3298                         } else {
3299                                 IPW_DEBUG_NOTIF("starting queue\n");
3300                                 netif_start_queue(priv->net_dev);
3301                         }
3302
3303                         ipw_reset_stats(priv);
3304                         /* Ensure the rate is updated immediately */
3305                         priv->last_rate = ipw_get_current_rate(priv);
3306                         schedule_work(&priv->gather_stats);
3307                         notify_wx_assoc_event(priv);
3308
3309 /*                      queue_delayed_work(priv->workqueue,
3310                                            &priv->request_scan,
3311                                            SCAN_ASSOCIATED_INTERVAL);
3312 */
3313                         break;
3314                 }
3315
3316                 case CMAS_AUTHENTICATED: {
3317                         if (priv->status & (STATUS_ASSOCIATED | STATUS_AUTH)) {
3318 #ifdef CONFIG_IPW_DEBUG
3319                                 struct notif_authenticate *auth = &notif->u.auth;
3320                                 IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE | IPW_DL_ASSOC,
3321                                           "deauthenticated: '%s' " MAC_FMT ": (0x%04X) - %s \n",
3322                                           escape_essid(priv->essid, priv->essid_len),
3323                                           MAC_ARG(priv->bssid),
3324                                           ntohs(auth->status),
3325                                           ipw_get_status_code(ntohs(auth->status)));
3326 #endif
3327
3328                                 priv->status &= ~(STATUS_ASSOCIATING |
3329                                                   STATUS_AUTH |
3330                                                   STATUS_ASSOCIATED);
3331
3332                                 netif_carrier_off(priv->net_dev);
3333                                 netif_stop_queue(priv->net_dev);
3334                                 queue_work(priv->workqueue, &priv->request_scan);
3335                                 notify_wx_assoc_event(priv);
3336                                 break;
3337                         }
3338
3339                         IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE | IPW_DL_ASSOC,
3340                                   "authenticated: '%s' " MAC_FMT "\n",
3341                                   escape_essid(priv->essid, priv->essid_len),
3342                                   MAC_ARG(priv->bssid));
3343                         break;
3344                 }
3345
3346                 case CMAS_INIT: {
3347                         IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE | IPW_DL_ASSOC,
3348                                   "disassociated: '%s' " MAC_FMT " \n",
3349                                   escape_essid(priv->essid, priv->essid_len),
3350                                   MAC_ARG(priv->bssid));
3351
3352                         priv->status &= ~(
3353                                 STATUS_DISASSOCIATING |
3354                                 STATUS_ASSOCIATING |
3355                                 STATUS_ASSOCIATED |
3356                                 STATUS_AUTH);
3357
3358                         netif_stop_queue(priv->net_dev);
3359                         if (!(priv->status & STATUS_ROAMING)) {
3360                                 netif_carrier_off(priv->net_dev);
3361                                 notify_wx_assoc_event(priv);
3362
3363                                 /* Cancel any queued work ... */
3364                                 cancel_delayed_work(&priv->request_scan);
3365                                 cancel_delayed_work(&priv->adhoc_check);
3366
3367                                 /* Queue up another scan... */
3368                                 queue_work(priv->workqueue,
3369                                            &priv->request_scan);
3370
3371                                 cancel_delayed_work(&priv->gather_stats);
3372                         } else {
3373                                 priv->status |= STATUS_ROAMING;
3374                                 queue_work(priv->workqueue,
3375                                            &priv->request_scan);
3376                         }
3377
3378                         ipw_reset_stats(priv);
3379                         break;
3380                 }
3381
3382                 default:
3383                         IPW_ERROR("assoc: unknown (%d)\n",
3384                                   assoc->state);
3385                         break;
3386                 }
3387
3388                 break;
3389         }
3390
3391         case HOST_NOTIFICATION_STATUS_AUTHENTICATE: {
3392                 struct notif_authenticate *auth = &notif->u.auth;
3393                 switch (auth->state) {
3394                 case CMAS_AUTHENTICATED:
3395                         IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE,
3396                                   "authenticated: '%s' " MAC_FMT " \n",
3397                                   escape_essid(priv->essid, priv->essid_len),
3398                                   MAC_ARG(priv->bssid));
3399                         priv->status |= STATUS_AUTH;
3400                         break;
3401
3402                 case CMAS_INIT:
3403                         if (priv->status & STATUS_AUTH) {
3404                                 IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE | IPW_DL_ASSOC,
3405                                           "authentication failed (0x%04X): %s\n",
3406                                           ntohs(auth->status),
3407                                           ipw_get_status_code(ntohs(auth->status)));
3408                         }
3409                         IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE | IPW_DL_ASSOC,
3410                                   "deauthenticated: '%s' " MAC_FMT "\n",
3411                                   escape_essid(priv->essid, priv->essid_len),
3412                                   MAC_ARG(priv->bssid));
3413
3414                         priv->status &= ~(STATUS_ASSOCIATING |
3415                                           STATUS_AUTH |
3416                                           STATUS_ASSOCIATED);
3417
3418                         netif_carrier_off(priv->net_dev);
3419                         netif_stop_queue(priv->net_dev);
3420                         queue_work(priv->workqueue, &priv->request_scan);
3421                         notify_wx_assoc_event(priv);
3422                         break;
3423
3424                 case CMAS_TX_AUTH_SEQ_1:
3425                         IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE | IPW_DL_ASSOC,
3426                                   "AUTH_SEQ_1\n");
3427                         break;
3428                 case CMAS_RX_AUTH_SEQ_2:
3429                         IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE | IPW_DL_ASSOC,
3430                                   "AUTH_SEQ_2\n");
3431                         break;
3432                 case CMAS_AUTH_SEQ_1_PASS:
3433                         IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE | IPW_DL_ASSOC,
3434                                   "AUTH_SEQ_1_PASS\n");
3435                         break;
3436                 case CMAS_AUTH_SEQ_1_FAIL:
3437                         IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE | IPW_DL_ASSOC,
3438                                   "AUTH_SEQ_1_FAIL\n");
3439                         break;
3440                 case CMAS_TX_AUTH_SEQ_3:
3441                         IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE | IPW_DL_ASSOC,
3442                                   "AUTH_SEQ_3\n");
3443                         break;
3444                 case CMAS_RX_AUTH_SEQ_4:
3445                         IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE | IPW_DL_ASSOC,
3446                                   "RX_AUTH_SEQ_4\n");
3447                         break;
3448                 case CMAS_AUTH_SEQ_2_PASS:
3449                         IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE | IPW_DL_ASSOC,
3450                                   "AUTH_SEQ_2_PASS\n");
3451                         break;
3452                 case CMAS_AUTH_SEQ_2_FAIL:
3453                         IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE | IPW_DL_ASSOC,
3454                                   "AUT_SEQ_2_FAIL\n");
3455                         break;
3456                 case CMAS_TX_ASSOC:
3457                         IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE | IPW_DL_ASSOC,
3458                                   "TX_ASSOC\n");
3459                         break;
3460                 case CMAS_RX_ASSOC_RESP:
3461                         IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE | IPW_DL_ASSOC,
3462                                   "RX_ASSOC_RESP\n");
3463                         break;
3464                 case CMAS_ASSOCIATED:
3465                         IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE | IPW_DL_ASSOC,
3466                                   "ASSOCIATED\n");
3467                         break;
3468                 default:
3469                         IPW_DEBUG_NOTIF("auth: failure - %d\n", auth->state);
3470                         break;
3471                 }
3472                 break;
3473         }
3474
3475         case HOST_NOTIFICATION_STATUS_SCAN_CHANNEL_RESULT: {
3476                 struct notif_channel_result *x = &notif->u.channel_result;
3477
3478                 if (notif->size == sizeof(*x)) {
3479                         IPW_DEBUG_SCAN("Scan result for channel %d\n",
3480                                        x->channel_num);
3481                 } else {
3482                         IPW_DEBUG_SCAN("Scan result of wrong size %d "
3483                                        "(should be %zd)\n",
3484                                        notif->size, sizeof(*x));
3485                 }
3486                 break;
3487         }
3488
3489         case HOST_NOTIFICATION_STATUS_SCAN_COMPLETED: {
3490                 struct notif_scan_complete* x = &notif->u.scan_complete;
3491                 if (notif->size == sizeof(*x)) {
3492                         IPW_DEBUG_SCAN("Scan completed: type %d, %d channels, "
3493                                        "%d status\n",
3494                                        x->scan_type,
3495                                        x->num_channels,
3496                                        x->status);
3497                 } else {
3498                         IPW_ERROR("Scan completed of wrong size %d "
3499                                   "(should be %zd)\n",
3500                                   notif->size, sizeof(*x));
3501                 }
3502
3503                 priv->status &= ~(STATUS_SCANNING | STATUS_SCAN_ABORTING);
3504
3505                 cancel_delayed_work(&priv->scan_check);
3506
3507                 if (!(priv->status & (STATUS_ASSOCIATED |
3508                                       STATUS_ASSOCIATING |
3509                                       STATUS_ROAMING |
3510                                       STATUS_DISASSOCIATING)))
3511                         queue_work(priv->workqueue, &priv->associate);
3512                 else if (priv->status & STATUS_ROAMING) {
3513                         /* If a scan completed and we are in roam mode, then
3514                          * the scan that completed was the one requested as a
3515                          * result of entering roam... so, schedule the
3516                          * roam work */
3517                         queue_work(priv->workqueue, &priv->roam);
3518                 } else if (priv->status & STATUS_SCAN_PENDING)
3519                         queue_work(priv->workqueue, &priv->request_scan);
3520
3521                 priv->ieee->scans++;
3522                 break;
3523         }
3524
3525         case HOST_NOTIFICATION_STATUS_FRAG_LENGTH: {
3526                 struct notif_frag_length *x = &notif->u.frag_len;
3527
3528                 if (notif->size == sizeof(*x)) {
3529                         IPW_ERROR("Frag length: %d\n", x->frag_length);
3530                 } else {
3531                         IPW_ERROR("Frag length of wrong size %d "
3532                                   "(should be %zd)\n",
3533                                   notif->size, sizeof(*x));
3534                 }
3535                 break;
3536         }
3537
3538         case HOST_NOTIFICATION_STATUS_LINK_DETERIORATION: {
3539                 struct notif_link_deterioration *x =
3540                         &notif->u.link_deterioration;
3541                 if (notif->size==sizeof(*x)) {
3542                         IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE,
3543                                   "link deterioration: '%s' " MAC_FMT " \n",
3544                                   escape_essid(priv->essid, priv->essid_len),
3545                                   MAC_ARG(priv->bssid));
3546                         memcpy(&priv->last_link_deterioration, x, sizeof(*x));
3547                 } else {
3548                         IPW_ERROR("Link Deterioration of wrong size %d "
3549                                   "(should be %zd)\n",
3550                                   notif->size, sizeof(*x));
3551                 }
3552                 break;
3553         }
3554
3555         case HOST_NOTIFICATION_DINO_CONFIG_RESPONSE: {
3556                 IPW_ERROR("Dino config\n");
3557                 if (priv->hcmd && priv->hcmd->cmd == HOST_CMD_DINO_CONFIG) {
3558                         /* TODO: Do anything special? */
3559                 } else {
3560                         IPW_ERROR("Unexpected DINO_CONFIG_RESPONSE\n");
3561                 }
3562                 break;
3563         }
3564
3565         case HOST_NOTIFICATION_STATUS_BEACON_STATE: {
3566                 struct notif_beacon_state *x = &notif->u.beacon_state;
3567                 if (notif->size != sizeof(*x)) {
3568                         IPW_ERROR("Beacon state of wrong size %d (should "
3569                                   "be %zd)\n", notif->size, sizeof(*x));
3570                         break;
3571                 }
3572
3573                 if (x->state == HOST_NOTIFICATION_STATUS_BEACON_MISSING) {
3574                         if (priv->status & STATUS_SCANNING) {
3575                                 /* Stop scan to keep fw from getting
3576                                  * stuck... */
3577                                 queue_work(priv->workqueue,
3578                                            &priv->abort_scan);
3579                         }
3580
3581                         if (x->number > priv->missed_beacon_threshold &&
3582                             priv->status & STATUS_ASSOCIATED) {
3583                                 IPW_DEBUG(IPW_DL_INFO | IPW_DL_NOTIF |
3584                                           IPW_DL_STATE,
3585                                           "Missed beacon: %d - disassociate\n",
3586                                           x->number);
3587                                 queue_work(priv->workqueue,
3588                                            &priv->disassociate);
3589                         } else if (x->number > priv->roaming_threshold) {
3590                                 IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE,
3591                                           "Missed beacon: %d - initiate "
3592                                           "roaming\n",
3593                                           x->number);
3594                                 queue_work(priv->workqueue,
3595                                            &priv->roam);
3596                         } else {
3597                                 IPW_DEBUG_NOTIF("Missed beacon: %d\n",
3598                                                 x->number);
3599                         }
3600
3601                         priv->notif_missed_beacons = x->number;
3602
3603                 }
3604
3605
3606                 break;
3607         }
3608
3609         case HOST_NOTIFICATION_STATUS_TGI_TX_KEY: {
3610                 struct notif_tgi_tx_key *x = &notif->u.tgi_tx_key;
3611                 if (notif->size==sizeof(*x)) {
3612                         IPW_ERROR("TGi Tx Key: state 0x%02x sec type "
3613                                   "0x%02x station %d\n",
3614                                   x->key_state,x->security_type,
3615                                   x->station_index);
3616                         break;
3617                 }
3618
3619                 IPW_ERROR("TGi Tx Key of wrong size %d (should be %zd)\n",
3620                           notif->size, sizeof(*x));
3621                 break;
3622         }
3623
3624         case HOST_NOTIFICATION_CALIB_KEEP_RESULTS: {
3625                 struct notif_calibration *x = &notif->u.calibration;
3626
3627                 if (notif->size == sizeof(*x)) {
3628                         memcpy(&priv->calib, x, sizeof(*x));
3629                         IPW_DEBUG_INFO("TODO: Calibration\n");
3630                         break;
3631                 }
3632
3633                 IPW_ERROR("Calibration of wrong size %d (should be %zd)\n",
3634                           notif->size, sizeof(*x));
3635                 break;
3636         }
3637
3638         case HOST_NOTIFICATION_NOISE_STATS: {
3639                 if (notif->size == sizeof(u32)) {
3640                         priv->last_noise = (u8)(notif->u.noise.value & 0xff);
3641                         average_add(&priv->average_noise, priv->last_noise);
3642                         break;
3643                 }
3644
3645                 IPW_ERROR("Noise stat is wrong size %d (should be %zd)\n",
3646                           notif->size, sizeof(u32));
3647                 break;
3648         }
3649
3650         default:
3651                 IPW_ERROR("Unknown notification: "
3652                           "subtype=%d,flags=0x%2x,size=%d\n",
3653                           notif->subtype, notif->flags, notif->size);
3654         }
3655 }
3656
3657 /**
3658  * Destroys all DMA structures and initialise them again
3659  *
3660  * @param priv
3661  * @return error code
3662  */
3663 static int ipw_queue_reset(struct ipw_priv *priv)
3664 {
3665         int rc = 0;
3666         /** @todo customize queue sizes */
3667         int nTx = 64, nTxCmd = 8;
3668         ipw_tx_queue_free(priv);
3669         /* Tx CMD queue */
3670         rc = ipw_queue_tx_init(priv, &priv->txq_cmd, nTxCmd,
3671                                CX2_TX_CMD_QUEUE_READ_INDEX,
3672                                CX2_TX_CMD_QUEUE_WRITE_INDEX,
3673                                CX2_TX_CMD_QUEUE_BD_BASE,
3674                                CX2_TX_CMD_QUEUE_BD_SIZE);
3675         if (rc) {
3676                 IPW_ERROR("Tx Cmd queue init failed\n");
3677                 goto error;
3678         }
3679         /* Tx queue(s) */
3680         rc = ipw_queue_tx_init(priv, &priv->txq[0], nTx,
3681                                CX2_TX_QUEUE_0_READ_INDEX,
3682                                CX2_TX_QUEUE_0_WRITE_INDEX,
3683                                CX2_TX_QUEUE_0_BD_BASE,
3684                                CX2_TX_QUEUE_0_BD_SIZE);
3685         if (rc) {
3686                 IPW_ERROR("Tx 0 queue init failed\n");
3687                 goto error;
3688         }
3689         rc = ipw_queue_tx_init(priv, &priv->txq[1], nTx,
3690                                CX2_TX_QUEUE_1_READ_INDEX,
3691                                CX2_TX_QUEUE_1_WRITE_INDEX,
3692                                CX2_TX_QUEUE_1_BD_BASE,
3693                                CX2_TX_QUEUE_1_BD_SIZE);
3694         if (rc) {
3695                 IPW_ERROR("Tx 1 queue init failed\n");
3696                 goto error;
3697         }
3698         rc = ipw_queue_tx_init(priv, &priv->txq[2], nTx,
3699                                CX2_TX_QUEUE_2_READ_INDEX,
3700                                CX2_TX_QUEUE_2_WRITE_INDEX,
3701                                CX2_TX_QUEUE_2_BD_BASE,
3702                                CX2_TX_QUEUE_2_BD_SIZE);
3703         if (rc) {
3704                 IPW_ERROR("Tx 2 queue init failed\n");
3705                 goto error;
3706         }
3707         rc = ipw_queue_tx_init(priv, &priv->txq[3], nTx,
3708                                CX2_TX_QUEUE_3_READ_INDEX,
3709                                CX2_TX_QUEUE_3_WRITE_INDEX,
3710                                CX2_TX_QUEUE_3_BD_BASE,
3711                                CX2_TX_QUEUE_3_BD_SIZE);
3712         if (rc) {
3713                 IPW_ERROR("Tx 3 queue init failed\n");
3714                 goto error;
3715         }
3716         /* statistics */
3717         priv->rx_bufs_min = 0;
3718         priv->rx_pend_max = 0;
3719         return rc;
3720
3721  error:
3722         ipw_tx_queue_free(priv);
3723         return rc;
3724 }
3725
3726 /**
3727  * Reclaim Tx queue entries no more used by NIC.
3728  *
3729  * When FW adwances 'R' index, all entries between old and
3730  * new 'R' index need to be reclaimed. As result, some free space
3731  * forms. If there is enough free space (> low mark), wake Tx queue.
3732  *
3733  * @note Need to protect against garbage in 'R' index
3734  * @param priv
3735  * @param txq
3736  * @param qindex
3737  * @return Number of used entries remains in the queue
3738  */
3739 static int ipw_queue_tx_reclaim(struct ipw_priv *priv,
3740                                 struct clx2_tx_queue *txq, int qindex)
3741 {
3742         u32 hw_tail;
3743         int used;
3744         struct clx2_queue *q = &txq->q;
3745
3746         hw_tail = ipw_read32(priv, q->reg_r);
3747         if (hw_tail >= q->n_bd) {
3748                 IPW_ERROR
3749                         ("Read index for DMA queue (%d) is out of range [0-%d)\n",
3750                          hw_tail, q->n_bd);
3751                 goto done;
3752         }
3753         for (; q->last_used != hw_tail;
3754              q->last_used = ipw_queue_inc_wrap(q->last_used, q->n_bd)) {
3755                 ipw_queue_tx_free_tfd(priv, txq);
3756                 priv->tx_packets++;
3757         }
3758  done:
3759         if (ipw_queue_space(q) > q->low_mark && qindex >= 0) {
3760                 __maybe_wake_tx(priv);
3761         }
3762         used = q->first_empty - q->last_used;
3763         if (used < 0)
3764                 used += q->n_bd;
3765
3766         return used;
3767 }
3768
3769 static int ipw_queue_tx_hcmd(struct ipw_priv *priv, int hcmd, void *buf,
3770                              int len, int sync)
3771 {
3772         struct clx2_tx_queue *txq = &priv->txq_cmd;
3773         struct clx2_queue *q = &txq->q;
3774         struct tfd_frame *tfd;
3775
3776         if (ipw_queue_space(q) < (sync ? 1 : 2)) {
3777                 IPW_ERROR("No space for Tx\n");
3778                 return -EBUSY;
3779         }
3780
3781         tfd = &txq->bd[q->first_empty];
3782         txq->txb[q->first_empty] = NULL;
3783
3784         memset(tfd, 0, sizeof(*tfd));
3785         tfd->control_flags.message_type = TX_HOST_COMMAND_TYPE;
3786         tfd->control_flags.control_bits = TFD_NEED_IRQ_MASK;
3787         priv->hcmd_seq++;
3788         tfd->u.cmd.index = hcmd;
3789         tfd->u.cmd.length = len;
3790         memcpy(tfd->u.cmd.payload, buf, len);
3791         q->first_empty = ipw_queue_inc_wrap(q->first_empty, q->n_bd);
3792         ipw_write32(priv, q->reg_w, q->first_empty);
3793         _ipw_read32(priv, 0x90);
3794
3795         return 0;
3796 }
3797
3798
3799
3800 /*
3801  * Rx theory of operation
3802  *
3803  * The host allocates 32 DMA target addresses and passes the host address
3804  * to the firmware at register CX2_RFDS_TABLE_LOWER + N * RFD_SIZE where N is
3805  * 0 to 31
3806  *
3807  * Rx Queue Indexes
3808  * The host/firmware share two index registers for managing the Rx buffers.
3809  *
3810  * The READ index maps to the first position that the firmware may be writing
3811  * to -- the driver can read up to (but not including) this position and get
3812  * good data.
3813  * The READ index is managed by the firmware once the card is enabled.
3814  *
3815  * The WRITE index maps to the last position the driver has read from -- the
3816  * position preceding WRITE is the last slot the firmware can place a packet.
3817  *
3818  * The queue is empty (no good data) if WRITE = READ - 1, and is full if
3819  * WRITE = READ.
3820  *
3821  * During initialization the host sets up the READ queue position to the first
3822  * INDEX position, and WRITE to the last (READ - 1 wrapped)
3823  *
3824  * When the firmware places a packet in a buffer it will advance the READ index
3825  * and fire the RX interrupt.  The driver can then query the READ index and
3826  * process as many packets as possible, moving the WRITE index forward as it
3827  * resets the Rx queue buffers with new memory.
3828  *
3829  * The management in the driver is as follows:
3830  * + A list of pre-allocated SKBs is stored in ipw->rxq->rx_free.  When
3831  *   ipw->rxq->free_count drops to or below RX_LOW_WATERMARK, work is scheduled
3832  *   to replensish the ipw->rxq->rx_free.
3833  * + In ipw_rx_queue_replenish (scheduled) if 'processed' != 'read' then the
3834  *   ipw->rxq is replenished and the READ INDEX is updated (updating the
3835  *   'processed' and 'read' driver indexes as well)
3836  * + A received packet is processed and handed to the kernel network stack,
3837  *   detached from the ipw->rxq.  The driver 'processed' index is updated.
3838  * + The Host/Firmware ipw->rxq is replenished at tasklet time from the rx_free
3839  *   list. If there are no allocated buffers in ipw->rxq->rx_free, the READ
3840  *   INDEX is not incremented and ipw->status(RX_STALLED) is set.  If there
3841  *   were enough free buffers and RX_STALLED is set it is cleared.
3842  *
3843  *
3844  * Driver sequence:
3845  *
3846  * ipw_rx_queue_alloc()       Allocates rx_free
3847  * ipw_rx_queue_replenish()   Replenishes rx_free list from rx_used, and calls
3848  *                            ipw_rx_queue_restock
3849  * ipw_rx_queue_restock()     Moves available buffers from rx_free into Rx
3850  *                            queue, updates firmware pointers, and updates
3851  *                            the WRITE index.  If insufficient rx_free buffers
3852  *                            are available, schedules ipw_rx_queue_replenish
3853  *
3854  * -- enable interrupts --
3855  * ISR - ipw_rx()             Detach ipw_rx_mem_buffers from pool up to the
3856  *                            READ INDEX, detaching the SKB from the pool.
3857  *                            Moves the packet buffer from queue to rx_used.
3858  *                            Calls ipw_rx_queue_restock to refill any empty
3859  *                            slots.
3860  * ...
3861  *
3862  */
3863
3864 /*
3865  * If there are slots in the RX queue that  need to be restocked,
3866  * and we have free pre-allocated buffers, fill the ranks as much
3867  * as we can pulling from rx_free.
3868  *
3869  * This moves the 'write' index forward to catch up with 'processed', and
3870  * also updates the memory address in the firmware to reference the new
3871  * target buffer.
3872  */
3873 static void ipw_rx_queue_restock(struct ipw_priv *priv)
3874 {
3875         struct ipw_rx_queue *rxq = priv->rxq;
3876         struct list_head *element;
3877         struct ipw_rx_mem_buffer *rxb;
3878         unsigned long flags;
3879         int write;
3880
3881         spin_lock_irqsave(&rxq->lock, flags);
3882         write = rxq->write;
3883         while ((rxq->write != rxq->processed) && (rxq->free_count)) {
3884                 element = rxq->rx_free.next;
3885                 rxb = list_entry(element, struct ipw_rx_mem_buffer, list);
3886                 list_del(element);
3887
3888                 ipw_write32(priv, CX2_RFDS_TABLE_LOWER + rxq->write * RFD_SIZE,
3889                             rxb->dma_addr);
3890                 rxq->queue[rxq->write] = rxb;
3891                 rxq->write = (rxq->write + 1) % RX_QUEUE_SIZE;
3892                 rxq->free_count--;
3893         }
3894         spin_unlock_irqrestore(&rxq->lock, flags);
3895
3896         /* If the pre-allocated buffer pool is dropping low, schedule to
3897          * refill it */
3898         if (rxq->free_count <= RX_LOW_WATERMARK)
3899                 queue_work(priv->workqueue, &priv->rx_replenish);
3900
3901         /* If we've added more space for the firmware to place data, tell it */
3902         if (write != rxq->write)
3903                 ipw_write32(priv, CX2_RX_WRITE_INDEX, rxq->write);
3904 }
3905
3906 /*
3907  * Move all used packet from rx_used to rx_free, allocating a new SKB for each.
3908  * Also restock the Rx queue via ipw_rx_queue_restock.
3909  *
3910  * This is called as a scheduled work item (except for during intialization)
3911  */
3912 static void ipw_rx_queue_replenish(void *data)
3913 {
3914         struct ipw_priv *priv = data;
3915         struct ipw_rx_queue *rxq = priv->rxq;
3916         struct list_head *element;
3917         struct ipw_rx_mem_buffer *rxb;
3918         unsigned long flags;
3919
3920         spin_lock_irqsave(&rxq->lock, flags);
3921         while (!list_empty(&rxq->rx_used)) {
3922                 element = rxq->rx_used.next;
3923                 rxb = list_entry(element, struct ipw_rx_mem_buffer, list);
3924                 rxb->skb = alloc_skb(CX2_RX_BUF_SIZE, GFP_ATOMIC);
3925                 if (!rxb->skb) {
3926                         printk(KERN_CRIT "%s: Can not allocate SKB buffers.\n",
3927                                priv->net_dev->name);
3928                         /* We don't reschedule replenish work here -- we will
3929                          * call the restock method and if it still needs
3930                          * more buffers it will schedule replenish */
3931                         break;
3932                 }
3933                 list_del(element);
3934
3935                 rxb->rxb = (struct ipw_rx_buffer *)rxb->skb->data;
3936                 rxb->dma_addr = pci_map_single(
3937                         priv->pci_dev, rxb->skb->data, CX2_RX_BUF_SIZE,
3938                         PCI_DMA_FROMDEVICE);
3939
3940                 list_add_tail(&rxb->list, &rxq->rx_free);
3941                 rxq->free_count++;
3942         }
3943         spin_unlock_irqrestore(&rxq->lock, flags);
3944
3945         ipw_rx_queue_restock(priv);
3946 }
3947
3948 /* Assumes that the skb field of the buffers in 'pool' is kept accurate.
3949  * If an SKB has been detached, the POOL needs to have it's SKB set to NULL
3950  * This free routine walks the list of POOL entries and if SKB is set to
3951  * non NULL it is unmapped and freed
3952  */
3953 static void ipw_rx_queue_free(struct ipw_priv *priv,
3954                               struct ipw_rx_queue *rxq)
3955 {
3956         int i;
3957
3958         if (!rxq)
3959                 return;
3960
3961         for (i = 0; i < RX_QUEUE_SIZE + RX_FREE_BUFFERS; i++) {
3962                 if (rxq->pool[i].skb != NULL) {
3963                         pci_unmap_single(priv->pci_dev, rxq->pool[i].dma_addr,
3964                                          CX2_RX_BUF_SIZE,
3965                                          PCI_DMA_FROMDEVICE);
3966                         dev_kfree_skb(rxq->pool[i].skb);
3967                 }
3968         }
3969
3970         kfree(rxq);
3971 }
3972
3973 static struct ipw_rx_queue *ipw_rx_queue_alloc(struct ipw_priv *priv)
3974 {
3975         struct ipw_rx_queue *rxq;
3976         int i;
3977
3978         rxq = (struct ipw_rx_queue *)kmalloc(sizeof(*rxq), GFP_KERNEL);
3979         memset(rxq, 0, sizeof(*rxq));
3980         spin_lock_init(&rxq->lock);
3981         INIT_LIST_HEAD(&rxq->rx_free);
3982         INIT_LIST_HEAD(&rxq->rx_used);
3983
3984         /* Fill the rx_used queue with _all_ of the Rx buffers */
3985         for (i = 0; i < RX_FREE_BUFFERS + RX_QUEUE_SIZE; i++)
3986                 list_add_tail(&rxq->pool[i].list, &rxq->rx_used);
3987
3988         /* Set us so that we have processed and used all buffers, but have
3989          * not restocked the Rx queue with fresh buffers */
3990         rxq->read = rxq->write = 0;
3991         rxq->processed = RX_QUEUE_SIZE - 1;
3992         rxq->free_count = 0;
3993
3994         return rxq;
3995 }
3996
3997 static int ipw_is_rate_in_mask(struct ipw_priv *priv, int ieee_mode, u8 rate)
3998 {
3999         rate &= ~IEEE80211_BASIC_RATE_MASK;
4000         if (ieee_mode == IEEE_A) {
4001                 switch (rate) {
4002                 case IEEE80211_OFDM_RATE_6MB:
4003                         return priv->rates_mask & IEEE80211_OFDM_RATE_6MB_MASK ?
4004                                 1 : 0;
4005                 case IEEE80211_OFDM_RATE_9MB:
4006                         return priv->rates_mask & IEEE80211_OFDM_RATE_9MB_MASK ?
4007                                 1 : 0;
4008                 case IEEE80211_OFDM_RATE_12MB:
4009                         return priv->rates_mask & IEEE80211_OFDM_RATE_12MB_MASK ?
4010                                 1 : 0;
4011                 case IEEE80211_OFDM_RATE_18MB:
4012                         return priv->rates_mask & IEEE80211_OFDM_RATE_18MB_MASK ?
4013                                 1 : 0;
4014                 case IEEE80211_OFDM_RATE_24MB:
4015                         return priv->rates_mask & IEEE80211_OFDM_RATE_24MB_MASK ?
4016                                 1 : 0;
4017                 case IEEE80211_OFDM_RATE_36MB:
4018                         return priv->rates_mask & IEEE80211_OFDM_RATE_36MB_MASK ?
4019                                 1 : 0;
4020                 case IEEE80211_OFDM_RATE_48MB:
4021                         return priv->rates_mask & IEEE80211_OFDM_RATE_48MB_MASK ?
4022                                 1 : 0;
4023                 case IEEE80211_OFDM_RATE_54MB:
4024                         return priv->rates_mask & IEEE80211_OFDM_RATE_54MB_MASK ?
4025                                 1 : 0;
4026                 default:
4027                         return 0;
4028                 }
4029         }
4030
4031         /* B and G mixed */
4032         switch (rate) {
4033         case IEEE80211_CCK_RATE_1MB:
4034                 return priv->rates_mask & IEEE80211_CCK_RATE_1MB_MASK ? 1 : 0;
4035         case IEEE80211_CCK_RATE_2MB:
4036                 return priv->rates_mask & IEEE80211_CCK_RATE_2MB_MASK ? 1 : 0;
4037         case IEEE80211_CCK_RATE_5MB:
4038                 return priv->rates_mask & IEEE80211_CCK_RATE_5MB_MASK ? 1 : 0;
4039         case IEEE80211_CCK_RATE_11MB:
4040                 return priv->rates_mask & IEEE80211_CCK_RATE_11MB_MASK ? 1 : 0;
4041         }
4042
4043         /* If we are limited to B modulations, bail at this point */
4044         if (ieee_mode == IEEE_B)
4045                 return 0;
4046
4047         /* G */
4048         switch (rate) {
4049         case IEEE80211_OFDM_RATE_6MB:
4050                 return priv->rates_mask & IEEE80211_OFDM_RATE_6MB_MASK ? 1 : 0;
4051         case IEEE80211_OFDM_RATE_9MB:
4052                 return priv->rates_mask & IEEE80211_OFDM_RATE_9MB_MASK ? 1 : 0;
4053         case IEEE80211_OFDM_RATE_12MB:
4054                 return priv->rates_mask & IEEE80211_OFDM_RATE_12MB_MASK ? 1 : 0;
4055         case IEEE80211_OFDM_RATE_18MB:
4056                 return priv->rates_mask & IEEE80211_OFDM_RATE_18MB_MASK ? 1 : 0;
4057         case IEEE80211_OFDM_RATE_24MB:
4058                 return priv->rates_mask & IEEE80211_OFDM_RATE_24MB_MASK ? 1 : 0;
4059         case IEEE80211_OFDM_RATE_36MB:
4060                 return priv->rates_mask & IEEE80211_OFDM_RATE_36MB_MASK ? 1 : 0;
4061         case IEEE80211_OFDM_RATE_48MB:
4062                 return priv->rates_mask & IEEE80211_OFDM_RATE_48MB_MASK ? 1 : 0;
4063         case IEEE80211_OFDM_RATE_54MB:
4064                 return priv->rates_mask & IEEE80211_OFDM_RATE_54MB_MASK ? 1 : 0;
4065         }
4066
4067         return 0;
4068 }
4069
4070 static int ipw_compatible_rates(struct ipw_priv *priv,
4071                                 const struct ieee80211_network *network,
4072                                 struct ipw_supported_rates *rates)
4073 {
4074         int num_rates, i;
4075
4076         memset(rates, 0, sizeof(*rates));
4077         num_rates = min(network->rates_len, (u8)IPW_MAX_RATES);
4078         rates->num_rates = 0;
4079         for (i = 0; i < num_rates; i++) {
4080                 if (!ipw_is_rate_in_mask(priv, network->mode, network->rates[i])) {
4081                         IPW_DEBUG_SCAN("Rate %02X masked : 0x%08X\n",
4082                                        network->rates[i], priv->rates_mask);
4083                         continue;
4084                 }
4085
4086                 rates->supported_rates[rates->num_rates++] = network->rates[i];
4087         }
4088
4089         num_rates = min(network->rates_ex_len, (u8)(IPW_MAX_RATES - num_rates));
4090         for (i = 0; i < num_rates; i++) {
4091                 if (!ipw_is_rate_in_mask(priv, network->mode, network->rates_ex[i])) {
4092                         IPW_DEBUG_SCAN("Rate %02X masked : 0x%08X\n",
4093                                        network->rates_ex[i], priv->rates_mask);
4094                         continue;
4095                 }
4096
4097                 rates->supported_rates[rates->num_rates++] = network->rates_ex[i];
4098         }
4099
4100         return rates->num_rates;
4101 }
4102
4103 static inline void ipw_copy_rates(struct ipw_supported_rates *dest,
4104                                   const struct ipw_supported_rates *src)
4105 {
4106         u8 i;
4107         for (i = 0; i < src->num_rates; i++)
4108                 dest->supported_rates[i] = src->supported_rates[i];
4109         dest->num_rates = src->num_rates;
4110 }
4111
4112 /* TODO: Look at sniffed packets in the air to determine if the basic rate
4113  * mask should ever be used -- right now all callers to add the scan rates are
4114  * set with the modulation = CCK, so BASIC_RATE_MASK is never set... */
4115 static void ipw_add_cck_scan_rates(struct ipw_supported_rates *rates,
4116                                u8 modulation, u32 rate_mask)
4117 {
4118         u8 basic_mask = (IEEE80211_OFDM_MODULATION == modulation) ?
4119                 IEEE80211_BASIC_RATE_MASK : 0;
4120
4121         if (rate_mask & IEEE80211_CCK_RATE_1MB_MASK)
4122                 rates->supported_rates[rates->num_rates++] =
4123                         IEEE80211_BASIC_RATE_MASK | IEEE80211_CCK_RATE_1MB;
4124
4125         if (rate_mask & IEEE80211_CCK_RATE_2MB_MASK)
4126                 rates->supported_rates[rates->num_rates++] =
4127                         IEEE80211_BASIC_RATE_MASK | IEEE80211_CCK_RATE_2MB;
4128
4129         if (rate_mask & IEEE80211_CCK_RATE_5MB_MASK)
4130                 rates->supported_rates[rates->num_rates++] = basic_mask |
4131                         IEEE80211_CCK_RATE_5MB;
4132
4133         if (rate_mask & IEEE80211_CCK_RATE_11MB_MASK)
4134                 rates->supported_rates[rates->num_rates++] = basic_mask |
4135                         IEEE80211_CCK_RATE_11MB;
4136 }
4137
4138 static void ipw_add_ofdm_scan_rates(struct ipw_supported_rates *rates,
4139                                 u8 modulation, u32 rate_mask)
4140 {
4141         u8 basic_mask = (IEEE80211_OFDM_MODULATION == modulation) ?
4142                 IEEE80211_BASIC_RATE_MASK : 0;
4143
4144         if (rate_mask & IEEE80211_OFDM_RATE_6MB_MASK)
4145                 rates->supported_rates[rates->num_rates++] = basic_mask |
4146                         IEEE80211_OFDM_RATE_6MB;
4147
4148         if (rate_mask & IEEE80211_OFDM_RATE_9MB_MASK)
4149                 rates->supported_rates[rates->num_rates++] =
4150                         IEEE80211_OFDM_RATE_9MB;
4151
4152         if (rate_mask & IEEE80211_OFDM_RATE_12MB_MASK)
4153                 rates->supported_rates[rates->num_rates++] = basic_mask |
4154                         IEEE80211_OFDM_RATE_12MB;
4155
4156         if (rate_mask & IEEE80211_OFDM_RATE_18MB_MASK)
4157                 rates->supported_rates[rates->num_rates++] =
4158                         IEEE80211_OFDM_RATE_18MB;
4159
4160         if (rate_mask & IEEE80211_OFDM_RATE_24MB_MASK)
4161                 rates->supported_rates[rates->num_rates++] = basic_mask |
4162                         IEEE80211_OFDM_RATE_24MB;
4163
4164         if (rate_mask & IEEE80211_OFDM_RATE_36MB_MASK)
4165                 rates->supported_rates[rates->num_rates++] =
4166                         IEEE80211_OFDM_RATE_36MB;
4167
4168         if (rate_mask & IEEE80211_OFDM_RATE_48MB_MASK)
4169                 rates->supported_rates[rates->num_rates++] =
4170                         IEEE80211_OFDM_RATE_48MB;
4171
4172         if (rate_mask & IEEE80211_OFDM_RATE_54MB_MASK)
4173                 rates->supported_rates[rates->num_rates++] =
4174                         IEEE80211_OFDM_RATE_54MB;
4175 }
4176
4177 struct ipw_network_match {
4178         struct ieee80211_network *network;
4179         struct ipw_supported_rates rates;
4180 };
4181
4182 static int ipw_best_network(
4183         struct ipw_priv *priv,
4184         struct ipw_network_match *match,
4185         struct ieee80211_network *network,
4186         int roaming)
4187 {
4188         struct ipw_supported_rates rates;
4189
4190         /* Verify that this network's capability is compatible with the
4191          * current mode (AdHoc or Infrastructure) */
4192         if ((priv->ieee->iw_mode == IW_MODE_INFRA &&
4193              !(network->capability & WLAN_CAPABILITY_ESS)) ||
4194             (priv->ieee->iw_mode == IW_MODE_ADHOC &&
4195              !(network->capability & WLAN_CAPABILITY_IBSS))) {
4196                 IPW_DEBUG_ASSOC("Network '%s (" MAC_FMT ")' excluded due to "
4197                                 "capability mismatch.\n",
4198                                 escape_essid(network->ssid, network->ssid_len),
4199                                 MAC_ARG(network->bssid));
4200                 return 0;
4201         }
4202
4203         /* If we do not have an ESSID for this AP, we can not associate with
4204          * it */
4205         if (network->flags & NETWORK_EMPTY_ESSID) {
4206                 IPW_DEBUG_ASSOC("Network '%s (" MAC_FMT ")' excluded "
4207                                 "because of hidden ESSID.\n",
4208                                 escape_essid(network->ssid, network->ssid_len),
4209                                 MAC_ARG(network->bssid));
4210                 return 0;
4211         }
4212
4213         if (unlikely(roaming)) {
4214                 /* If we are roaming, then ensure check if this is a valid
4215                  * network to try and roam to */
4216                 if ((network->ssid_len != match->network->ssid_len) ||
4217                     memcmp(network->ssid, match->network->ssid,
4218                            network->ssid_len)) {
4219                         IPW_DEBUG_ASSOC("Netowrk '%s (" MAC_FMT ")' excluded "
4220                                         "because of non-network ESSID.\n",
4221                                         escape_essid(network->ssid,
4222                                                      network->ssid_len),
4223                                         MAC_ARG(network->bssid));
4224                         return 0;
4225                 }
4226         } else {
4227                 /* If an ESSID has been configured then compare the broadcast
4228                  * ESSID to ours */
4229                 if ((priv->config & CFG_STATIC_ESSID) &&
4230                     ((network->ssid_len != priv->essid_len) ||
4231                      memcmp(network->ssid, priv->essid,
4232                             min(network->ssid_len, priv->essid_len)))) {
4233                         char escaped[IW_ESSID_MAX_SIZE * 2 + 1];
4234                         strncpy(escaped, escape_essid(
4235                                         network->ssid, network->ssid_len),
4236                                 sizeof(escaped));
4237                         IPW_DEBUG_ASSOC("Network '%s (" MAC_FMT ")' excluded "
4238                                         "because of ESSID mismatch: '%s'.\n",
4239                                         escaped, MAC_ARG(network->bssid),
4240                                         escape_essid(priv->essid, priv->essid_len));
4241                         return 0;
4242                 }
4243         }
4244
4245         /* If the old network rate is better than this one, don't bother
4246          * testing everything else. */
4247         if (match->network && match->network->stats.rssi >
4248             network->stats.rssi) {
4249                 char escaped[IW_ESSID_MAX_SIZE * 2 + 1];
4250                 strncpy(escaped,
4251                         escape_essid(network->ssid, network->ssid_len),
4252                         sizeof(escaped));
4253                 IPW_DEBUG_ASSOC("Network '%s (" MAC_FMT ")' excluded because "
4254                                 "'%s (" MAC_FMT ")' has a stronger signal.\n",
4255                                 escaped, MAC_ARG(network->bssid),
4256                                 escape_essid(match->network->ssid,
4257                                              match->network->ssid_len),
4258                                 MAC_ARG(match->network->bssid));
4259                 return 0;
4260         }
4261
4262         /* If this network has already had an association attempt within the
4263          * last 3 seconds, do not try and associate again... */
4264         if (network->last_associate &&
4265             time_after(network->last_associate + (HZ * 5UL), jiffies)) {
4266                 IPW_DEBUG_ASSOC("Network '%s (" MAC_FMT ")' excluded "
4267                                 "because of storming (%lu since last "
4268                                 "assoc attempt).\n",
4269                                 escape_essid(network->ssid, network->ssid_len),
4270                                 MAC_ARG(network->bssid),
4271                                 (jiffies - network->last_associate) / HZ);
4272                 return 0;
4273         }
4274
4275         /* Now go through and see if the requested network is valid... */
4276         if (priv->ieee->scan_age != 0 &&
4277             jiffies - network->last_scanned > priv->ieee->scan_age) {
4278                 IPW_DEBUG_ASSOC("Network '%s (" MAC_FMT ")' excluded "
4279                                 "because of age: %lums.\n",
4280                                 escape_essid(network->ssid, network->ssid_len),
4281                                 MAC_ARG(network->bssid),
4282                                 (jiffies - network->last_scanned) / (HZ / 100));
4283                 return 0;
4284         }
4285
4286         if ((priv->config & CFG_STATIC_CHANNEL) &&
4287             (network->channel != priv->channel)) {
4288                 IPW_DEBUG_ASSOC("Network '%s (" MAC_FMT ")' excluded "
4289                                 "because of channel mismatch: %d != %d.\n",
4290                                 escape_essid(network->ssid, network->ssid_len),
4291                                 MAC_ARG(network->bssid),
4292                                 network->channel, priv->channel);
4293                 return 0;
4294         }
4295
4296         /* Verify privacy compatability */
4297         if (((priv->capability & CAP_PRIVACY_ON) ? 1 : 0) !=
4298             ((network->capability & WLAN_CAPABILITY_PRIVACY) ? 1 : 0)) {
4299                 IPW_DEBUG_ASSOC("Network '%s (" MAC_FMT ")' excluded "
4300                                 "because of privacy mismatch: %s != %s.\n",
4301                                 escape_essid(network->ssid, network->ssid_len),
4302                                 MAC_ARG(network->bssid),
4303                                 priv->capability & CAP_PRIVACY_ON ? "on" :
4304                                 "off",
4305                                 network->capability &
4306                                 WLAN_CAPABILITY_PRIVACY ?"on" : "off");
4307                 return 0;
4308         }
4309
4310         if ((priv->config & CFG_STATIC_BSSID) &&
4311             memcmp(network->bssid, priv->bssid, ETH_ALEN)) {
4312                 IPW_DEBUG_ASSOC("Network '%s (" MAC_FMT ")' excluded "
4313                                 "because of BSSID mismatch: " MAC_FMT ".\n",
4314                                 escape_essid(network->ssid, network->ssid_len),
4315                                 MAC_ARG(network->bssid),
4316                                 MAC_ARG(priv->bssid));
4317                 return 0;
4318         }
4319
4320         /* Filter out any incompatible freq / mode combinations */
4321         if (!ieee80211_is_valid_mode(priv->ieee, network->mode)) {
4322                 IPW_DEBUG_ASSOC("Network '%s (" MAC_FMT ")' excluded "
4323                                 "because of invalid frequency/mode "
4324                                 "combination.\n",
4325                                 escape_essid(network->ssid, network->ssid_len),
4326                                 MAC_ARG(network->bssid));
4327                 return 0;
4328         }
4329
4330         ipw_compatible_rates(priv, network, &rates);
4331         if (rates.num_rates == 0) {
4332                 IPW_DEBUG_ASSOC("Network '%s (" MAC_FMT ")' excluded "
4333                                 "because of no compatible rates.\n",
4334                                 escape_essid(network->ssid, network->ssid_len),
4335                                 MAC_ARG(network->bssid));
4336                 return 0;
4337         }
4338
4339         /* TODO: Perform any further minimal comparititive tests.  We do not
4340          * want to put too much policy logic here; intelligent scan selection
4341          * should occur within a generic IEEE 802.11 user space tool.  */
4342
4343         /* Set up 'new' AP to this network */
4344         ipw_copy_rates(&match->rates, &rates);
4345         match->network = network;
4346
4347         IPW_DEBUG_ASSOC("Network '%s (" MAC_FMT ")' is a viable match.\n",
4348                         escape_essid(network->ssid, network->ssid_len),
4349                         MAC_ARG(network->bssid));
4350
4351         return 1;
4352 }
4353
4354
4355 static void ipw_adhoc_create(struct ipw_priv *priv,
4356                             struct ieee80211_network *network)
4357 {
4358         /*
4359          * For the purposes of scanning, we can set our wireless mode
4360          * to trigger scans across combinations of bands, but when it
4361          * comes to creating a new ad-hoc network, we have tell the FW
4362          * exactly which band to use.
4363          *
4364          * We also have the possibility of an invalid channel for the
4365          * chossen band.  Attempting to create a new ad-hoc network
4366          * with an invalid channel for wireless mode will trigger a
4367          * FW fatal error.
4368          */
4369         network->mode = is_valid_channel(priv->ieee->mode, priv->channel);
4370         if (network->mode) {
4371                 network->channel = priv->channel;
4372         } else {
4373                 IPW_WARNING("Overriding invalid channel\n");
4374                 if (priv->ieee->mode & IEEE_A) {
4375                         network->mode = IEEE_A;
4376                         priv->channel = band_a_active_channel[0];
4377                 } else if (priv->ieee->mode & IEEE_G) {
4378                         network->mode = IEEE_G;
4379                         priv->channel = band_b_active_channel[0];
4380                 } else {
4381                         network->mode = IEEE_B;
4382                         priv->channel = band_b_active_channel[0];
4383                 }
4384         }
4385
4386         network->channel = priv->channel;
4387         priv->config |= CFG_ADHOC_PERSIST;
4388         ipw_create_bssid(priv, network->bssid);
4389         network->ssid_len = priv->essid_len;
4390         memcpy(network->ssid, priv->essid, priv->essid_len);
4391         memset(&network->stats, 0, sizeof(network->stats));
4392         network->capability = WLAN_CAPABILITY_IBSS;
4393         if (priv->capability & CAP_PRIVACY_ON)
4394                 network->capability |= WLAN_CAPABILITY_PRIVACY;
4395         network->rates_len = min(priv->rates.num_rates, MAX_RATES_LENGTH);
4396         memcpy(network->rates, priv->rates.supported_rates,
4397                network->rates_len);
4398         network->rates_ex_len = priv->rates.num_rates - network->rates_len;
4399         memcpy(network->rates_ex,
4400                &priv->rates.supported_rates[network->rates_len],
4401                network->rates_ex_len);
4402         network->last_scanned = 0;
4403         network->flags = 0;
4404         network->last_associate = 0;
4405         network->time_stamp[0] = 0;
4406         network->time_stamp[1] = 0;
4407         network->beacon_interval = 100; /* Default */
4408         network->listen_interval = 10;  /* Default */
4409         network->atim_window = 0;       /* Default */
4410 #ifdef CONFIG_IEEE80211_WPA
4411         network->wpa_ie_len = 0;
4412         network->rsn_ie_len = 0;
4413 #endif /* CONFIG_IEEE80211_WPA */
4414 }
4415
4416 static void ipw_send_wep_keys(struct ipw_priv *priv)
4417 {
4418         struct ipw_wep_key *key;
4419         int i;
4420         struct host_cmd cmd = {
4421                 .cmd = IPW_CMD_WEP_KEY,
4422                 .len = sizeof(*key)
4423         };
4424
4425         key = (struct ipw_wep_key *)&cmd.param;
4426         key->cmd_id = DINO_CMD_WEP_KEY;
4427         key->seq_num = 0;
4428
4429         for (i = 0; i < 4; i++) {
4430                 key->key_index = i;
4431                 if (!(priv->sec.flags & (1 << i))) {
4432                         key->key_size = 0;
4433                 } else {
4434                         key->key_size = priv->sec.key_sizes[i];
4435                         memcpy(key->key, priv->sec.keys[i], key->key_size);
4436                 }
4437
4438                 if (ipw_send_cmd(priv, &cmd)) {
4439                         IPW_ERROR("failed to send WEP_KEY command\n");
4440                         return;
4441                 }
4442         }
4443 }
4444
4445 static void ipw_adhoc_check(void *data)
4446 {
4447         struct ipw_priv *priv = data;
4448
4449         if (priv->missed_adhoc_beacons++ > priv->missed_beacon_threshold &&
4450             !(priv->config & CFG_ADHOC_PERSIST)) {
4451                 IPW_DEBUG_SCAN("Disassociating due to missed beacons\n");
4452                 ipw_remove_current_network(priv);
4453                 ipw_disassociate(priv);
4454                 return;
4455         }
4456
4457         queue_delayed_work(priv->workqueue, &priv->adhoc_check,
4458                            priv->assoc_request.beacon_interval);
4459 }
4460
4461 #ifdef CONFIG_IPW_DEBUG
4462 static void ipw_debug_config(struct ipw_priv *priv)
4463 {
4464         IPW_DEBUG_INFO("Scan completed, no valid APs matched "
4465                        "[CFG 0x%08X]\n", priv->config);
4466         if (priv->config & CFG_STATIC_CHANNEL)
4467                 IPW_DEBUG_INFO("Channel locked to %d\n",
4468                                priv->channel);
4469         else
4470                 IPW_DEBUG_INFO("Channel unlocked.\n");
4471         if (priv->config & CFG_STATIC_ESSID)
4472                 IPW_DEBUG_INFO("ESSID locked to '%s'\n",
4473                                escape_essid(priv->essid,
4474                                             priv->essid_len));
4475         else
4476                 IPW_DEBUG_INFO("ESSID unlocked.\n");
4477         if (priv->config & CFG_STATIC_BSSID)
4478                 IPW_DEBUG_INFO("BSSID locked to %d\n", priv->channel);
4479         else
4480                 IPW_DEBUG_INFO("BSSID unlocked.\n");
4481         if (priv->capability & CAP_PRIVACY_ON)
4482                 IPW_DEBUG_INFO("PRIVACY on\n");
4483         else
4484                 IPW_DEBUG_INFO("PRIVACY off\n");
4485         IPW_DEBUG_INFO("RATE MASK: 0x%08X\n", priv->rates_mask);
4486 }
4487 #else
4488 #define ipw_debug_config(x) do {} while (0);
4489 #endif
4490
4491 static inline void ipw_set_fixed_rate(struct ipw_priv *priv,
4492                                       struct ieee80211_network *network)
4493 {
4494         /* TODO: Verify that this works... */
4495         struct ipw_fixed_rate fr = {
4496                 .tx_rates = priv->rates_mask
4497         };
4498         u32 reg;
4499         u16 mask = 0;
4500
4501         /* Identify 'current FW band' and match it with the fixed
4502          * Tx rates */
4503
4504         switch (priv->ieee->freq_band) {
4505         case IEEE80211_52GHZ_BAND: /* A only */
4506                 /* IEEE_A */
4507                 if (priv->rates_mask & ~IEEE80211_OFDM_RATES_MASK) {
4508                         /* Invalid fixed rate mask */
4509                         fr.tx_rates = 0;
4510                         break;
4511                 }
4512
4513                 fr.tx_rates >>= IEEE80211_OFDM_SHIFT_MASK_A;
4514                 break;
4515
4516         default: /* 2.4Ghz or Mixed */
4517                 /* IEEE_B */
4518                 if (network->mode == IEEE_B) {
4519                         if (fr.tx_rates & ~IEEE80211_CCK_RATES_MASK) {
4520                                 /* Invalid fixed rate mask */
4521                                 fr.tx_rates = 0;
4522                         }
4523                         break;
4524                 }
4525
4526                 /* IEEE_G */
4527                 if (fr.tx_rates & ~(IEEE80211_CCK_RATES_MASK |
4528                                     IEEE80211_OFDM_RATES_MASK)) {
4529                         /* Invalid fixed rate mask */
4530                         fr.tx_rates = 0;
4531                         break;
4532                 }
4533
4534                 if (IEEE80211_OFDM_RATE_6MB_MASK & fr.tx_rates) {
4535                         mask |= (IEEE80211_OFDM_RATE_6MB_MASK >> 1);
4536                         fr.tx_rates &= ~IEEE80211_OFDM_RATE_6MB_MASK;
4537                 }
4538
4539                 if (IEEE80211_OFDM_RATE_9MB_MASK & fr.tx_rates) {
4540                         mask |= (IEEE80211_OFDM_RATE_9MB_MASK >> 1);
4541                         fr.tx_rates &= ~IEEE80211_OFDM_RATE_9MB_MASK;
4542                 }
4543
4544                 if (IEEE80211_OFDM_RATE_12MB_MASK & fr.tx_rates) {
4545                         mask |= (IEEE80211_OFDM_RATE_12MB_MASK >> 1);
4546                         fr.tx_rates &= ~IEEE80211_OFDM_RATE_12MB_MASK;
4547                 }
4548
4549                 fr.tx_rates |= mask;
4550                 break;
4551         }
4552
4553         reg = ipw_read32(priv, IPW_MEM_FIXED_OVERRIDE);
4554         ipw_write_reg32(priv, reg, *(u32*)&fr);
4555 }
4556
4557 static int ipw_associate_network(struct ipw_priv *priv,
4558                                  struct ieee80211_network *network,
4559                                  struct ipw_supported_rates *rates,
4560                                  int roaming)
4561 {
4562         int err;
4563
4564         if (priv->config & CFG_FIXED_RATE)
4565                 ipw_set_fixed_rate(priv, network);
4566
4567         if (!(priv->config & CFG_STATIC_ESSID)) {
4568                 priv->essid_len = min(network->ssid_len,
4569                                       (u8)IW_ESSID_MAX_SIZE);
4570                 memcpy(priv->essid, network->ssid, priv->essid_len);
4571         }
4572
4573         network->last_associate = jiffies;
4574
4575         memset(&priv->assoc_request, 0, sizeof(priv->assoc_request));
4576         priv->assoc_request.channel = network->channel;
4577         if ((priv->capability & CAP_PRIVACY_ON) &&
4578             (priv->capability & CAP_SHARED_KEY)) {
4579                 priv->assoc_request.auth_type = AUTH_SHARED_KEY;
4580                 priv->assoc_request.auth_key = priv->sec.active_key;
4581         } else {
4582                 priv->assoc_request.auth_type = AUTH_OPEN;
4583                 priv->assoc_request.auth_key = 0;
4584         }
4585
4586         if (priv->capability & CAP_PRIVACY_ON)
4587                 ipw_send_wep_keys(priv);
4588
4589         /*
4590          * It is valid for our ieee device to support multiple modes, but
4591          * when it comes to associating to a given network we have to choose
4592          * just one mode.
4593          */
4594         if (network->mode & priv->ieee->mode & IEEE_A)
4595                 priv->assoc_request.ieee_mode = IPW_A_MODE;
4596         else if (network->mode & priv->ieee->mode & IEEE_G)
4597                 priv->assoc_request.ieee_mode = IPW_G_MODE;
4598         else if (network->mode & priv->ieee->mode & IEEE_B)
4599                 priv->assoc_request.ieee_mode = IPW_B_MODE;
4600
4601         IPW_DEBUG_ASSOC("%sssocation attempt: '%s', channel %d, "
4602                         "802.11%c [%d], enc=%s%s%s%c%c\n",
4603                         roaming ? "Rea" : "A",
4604                         escape_essid(priv->essid, priv->essid_len),
4605                         network->channel,
4606                         ipw_modes[priv->assoc_request.ieee_mode],
4607                         rates->num_rates,
4608                         priv->capability & CAP_PRIVACY_ON ? "on " : "off",
4609                         priv->capability & CAP_PRIVACY_ON ?
4610                         (priv->capability & CAP_SHARED_KEY ? "(shared)" :
4611                          "(open)") : "",
4612                         priv->capability & CAP_PRIVACY_ON ? " key=" : "",
4613                         priv->capability & CAP_PRIVACY_ON ?
4614                         '1' + priv->sec.active_key : '.',
4615                         priv->capability & CAP_PRIVACY_ON ?
4616                         '.' : ' ');
4617
4618         priv->assoc_request.beacon_interval = network->beacon_interval;
4619         if ((priv->ieee->iw_mode == IW_MODE_ADHOC) &&
4620             (network->time_stamp[0] == 0) &&
4621             (network->time_stamp[1] == 0)) {
4622                 priv->assoc_request.assoc_type = HC_IBSS_START;
4623                 priv->assoc_request.assoc_tsf_msw = 0;
4624                 priv->assoc_request.assoc_tsf_lsw = 0;
4625         } else {
4626                 if (unlikely(roaming))
4627                         priv->assoc_request.assoc_type = HC_REASSOCIATE;
4628                 else
4629                         priv->assoc_request.assoc_type = HC_ASSOCIATE;
4630                 priv->assoc_request.assoc_tsf_msw = network->time_stamp[1];
4631                 priv->assoc_request.assoc_tsf_lsw = network->time_stamp[0];
4632         }
4633
4634         memcpy(&priv->assoc_request.bssid, network->bssid, ETH_ALEN);
4635
4636         if (priv->ieee->iw_mode == IW_MODE_ADHOC) {
4637                 memset(&priv->assoc_request.dest, 0xFF, ETH_ALEN);
4638                 priv->assoc_request.atim_window = network->atim_window;
4639         } else {
4640                 memcpy(&priv->assoc_request.dest, network->bssid,
4641                        ETH_ALEN);
4642                 priv->assoc_request.atim_window = 0;
4643         }
4644
4645         priv->assoc_request.capability = network->capability;
4646         priv->assoc_request.listen_interval = network->listen_interval;
4647
4648         err = ipw_send_ssid(priv, priv->essid, priv->essid_len);
4649         if (err) {
4650                 IPW_DEBUG_HC("Attempt to send SSID command failed.\n");
4651                 return err;
4652         }
4653
4654         rates->ieee_mode = priv->assoc_request.ieee_mode;
4655         rates->purpose = IPW_RATE_CONNECT;
4656         ipw_send_supported_rates(priv, rates);
4657
4658         if (priv->assoc_request.ieee_mode == IPW_G_MODE)
4659                 priv->sys_config.dot11g_auto_detection = 1;
4660         else
4661                 priv->sys_config.dot11g_auto_detection = 0;
4662         err = ipw_send_system_config(priv, &priv->sys_config);
4663         if (err) {
4664                 IPW_DEBUG_HC("Attempt to send sys config command failed.\n");
4665                 return err;
4666         }
4667
4668         IPW_DEBUG_ASSOC("Association sensitivity: %d\n", network->stats.rssi);
4669         err = ipw_set_sensitivity(priv, network->stats.rssi);
4670         if (err) {
4671                 IPW_DEBUG_HC("Attempt to send associate command failed.\n");
4672                 return err;
4673         }
4674
4675         /*
4676          * If preemption is enabled, it is possible for the association
4677          * to complete before we return from ipw_send_associate.  Therefore
4678          * we have to be sure and update our priviate data first.
4679          */
4680         priv->channel = network->channel;
4681         memcpy(priv->bssid, network->bssid, ETH_ALEN);
4682         priv->status |= STATUS_ASSOCIATING;
4683         priv->status &= ~STATUS_SECURITY_UPDATED;
4684
4685         priv->assoc_network = network;
4686
4687         err = ipw_send_associate(priv, &priv->assoc_request);
4688         if (err) {
4689                 IPW_DEBUG_HC("Attempt to send associate command failed.\n");
4690                 return err;
4691         }
4692
4693         IPW_DEBUG(IPW_DL_STATE, "associating: '%s' " MAC_FMT " \n",
4694                   escape_essid(priv->essid, priv->essid_len),
4695                   MAC_ARG(priv->bssid));
4696
4697         return 0;
4698 }
4699
4700 static void ipw_roam(void *data)
4701 {
4702         struct ipw_priv *priv = data;
4703         struct ieee80211_network *network = NULL;
4704         struct ipw_network_match match = {
4705                 .network = priv->assoc_network
4706         };
4707
4708         /* The roaming process is as follows:
4709          *
4710          * 1.  Missed beacon threshold triggers the roaming process by
4711          *     setting the status ROAM bit and requesting a scan.
4712          * 2.  When the scan completes, it schedules the ROAM work
4713          * 3.  The ROAM work looks at all of the known networks for one that
4714          *     is a better network than the currently associated.  If none
4715          *     found, the ROAM process is over (ROAM bit cleared)
4716          * 4.  If a better network is found, a disassociation request is
4717          *     sent.
4718          * 5.  When the disassociation completes, the roam work is again
4719          *     scheduled.  The second time through, the driver is no longer
4720          *     associated, and the newly selected network is sent an
4721          *     association request.
4722          * 6.  At this point ,the roaming process is complete and the ROAM
4723          *     status bit is cleared.
4724          */
4725
4726         /* If we are no longer associated, and the roaming bit is no longer
4727          * set, then we are not actively roaming, so just return */
4728         if (!(priv->status & (STATUS_ASSOCIATED | STATUS_ROAMING)))
4729                 return;
4730
4731         if (priv->status & STATUS_ASSOCIATED) {
4732                 /* First pass through ROAM process -- look for a better
4733                  * network */
4734                 u8 rssi = priv->assoc_network->stats.rssi;
4735                 priv->assoc_network->stats.rssi = -128;
4736                 list_for_each_entry(network, &priv->ieee->network_list, list) {
4737                         if (network != priv->assoc_network)
4738                                 ipw_best_network(priv, &match, network, 1);
4739                 }
4740                 priv->assoc_network->stats.rssi = rssi;
4741
4742                 if (match.network == priv->assoc_network) {
4743                         IPW_DEBUG_ASSOC("No better APs in this network to "
4744                                         "roam to.\n");
4745                         priv->status &= ~STATUS_ROAMING;
4746                         ipw_debug_config(priv);
4747                         return;
4748                 }
4749
4750                 ipw_send_disassociate(priv, 1);
4751                 priv->assoc_network = match.network;
4752
4753                 return;
4754         }
4755
4756         /* Second pass through ROAM process -- request association */
4757         ipw_compatible_rates(priv, priv->assoc_network, &match.rates);
4758         ipw_associate_network(priv, priv->assoc_network, &match.rates, 1);
4759         priv->status &= ~STATUS_ROAMING;
4760 }
4761
4762 static void ipw_associate(void *data)
4763 {
4764         struct ipw_priv *priv = data;
4765
4766         struct ieee80211_network *network = NULL;
4767         struct ipw_network_match match = {
4768                 .network = NULL
4769         };
4770         struct ipw_supported_rates *rates;
4771         struct list_head *element;
4772
4773         if (!(priv->config & CFG_ASSOCIATE) &&
4774             !(priv->config & (CFG_STATIC_ESSID |
4775                               CFG_STATIC_CHANNEL |
4776                               CFG_STATIC_BSSID))) {
4777                 IPW_DEBUG_ASSOC("Not attempting association (associate=0)\n");
4778                 return;
4779         }
4780
4781         list_for_each_entry(network, &priv->ieee->network_list, list)
4782                 ipw_best_network(priv, &match, network, 0);
4783
4784         network = match.network;
4785         rates = &match.rates;
4786
4787         if (network == NULL &&
4788             priv->ieee->iw_mode == IW_MODE_ADHOC &&
4789             priv->config & CFG_ADHOC_CREATE &&
4790             priv->config & CFG_STATIC_ESSID &&
4791             !list_empty(&priv->ieee->network_free_list)) {
4792                 element = priv->ieee->network_free_list.next;
4793                 network = list_entry(element, struct ieee80211_network,
4794                                      list);
4795                 ipw_adhoc_create(priv, network);
4796                 rates = &priv->rates;
4797                 list_del(element);
4798                 list_add_tail(&network->list, &priv->ieee->network_list);
4799         }
4800
4801         /* If we reached the end of the list, then we don't have any valid
4802          * matching APs */
4803         if (!network) {
4804                 ipw_debug_config(priv);
4805
4806                 queue_delayed_work(priv->workqueue, &priv->request_scan,
4807                                    SCAN_INTERVAL);
4808
4809                 return;
4810         }
4811
4812         ipw_associate_network(priv, network, rates, 0);
4813 }
4814
4815 static inline void ipw_handle_data_packet(struct ipw_priv *priv,
4816                                               struct ipw_rx_mem_buffer *rxb,
4817                                               struct ieee80211_rx_stats *stats)
4818 {
4819         struct ipw_rx_packet *pkt = (struct ipw_rx_packet *)rxb->skb->data;
4820
4821         /* We received data from the HW, so stop the watchdog */
4822         priv->net_dev->trans_start = jiffies;
4823
4824         /* We only process data packets if the
4825          * interface is open */
4826         if (unlikely((pkt->u.frame.length + IPW_RX_FRAME_SIZE) >
4827                      skb_tailroom(rxb->skb))) {
4828                 priv->ieee->stats.rx_errors++;
4829                 priv->wstats.discard.misc++;
4830                 IPW_DEBUG_DROP("Corruption detected! Oh no!\n");
4831                 return;
4832         } else if (unlikely(!netif_running(priv->net_dev))) {
4833                 priv->ieee->stats.rx_dropped++;
4834                 priv->wstats.discard.misc++;
4835                 IPW_DEBUG_DROP("Dropping packet while interface is not up.\n");
4836                 return;
4837         }
4838
4839         /* Advance skb->data to the start of the actual payload */
4840         skb_reserve(rxb->skb, offsetof(struct ipw_rx_packet, u.frame.data));
4841
4842         /* Set the size of the skb to the size of the frame */
4843         skb_put(rxb->skb, pkt->u.frame.length);
4844
4845         IPW_DEBUG_RX("Rx packet of %d bytes.\n", rxb->skb->len);
4846
4847         if (!ieee80211_rx(priv->ieee, rxb->skb, stats))
4848                 priv->ieee->stats.rx_errors++;
4849         else /* ieee80211_rx succeeded, so it now owns the SKB */
4850                 rxb->skb = NULL;
4851 }
4852
4853
4854 /*
4855  * Main entry function for recieving a packet with 80211 headers.  This
4856  * should be called when ever the FW has notified us that there is a new
4857  * skb in the recieve queue.
4858  */
4859 static void ipw_rx(struct ipw_priv *priv)
4860 {
4861         struct ipw_rx_mem_buffer *rxb;
4862         struct ipw_rx_packet *pkt;
4863         struct ieee80211_hdr *header;
4864         u32 r, w, i;
4865         u8 network_packet;
4866
4867         r = ipw_read32(priv, CX2_RX_READ_INDEX);
4868         w = ipw_read32(priv, CX2_RX_WRITE_INDEX);
4869         i = (priv->rxq->processed + 1) % RX_QUEUE_SIZE;
4870
4871         while (i != r) {
4872                 rxb = priv->rxq->queue[i];
4873 #ifdef CONFIG_IPW_DEBUG
4874                 if (unlikely(rxb == NULL)) {
4875                         printk(KERN_CRIT "Queue not allocated!\n");
4876                         break;
4877                 }
4878 #endif
4879                 priv->rxq->queue[i] = NULL;
4880
4881                 pci_dma_sync_single_for_cpu(priv->pci_dev, rxb->dma_addr,
4882                                             CX2_RX_BUF_SIZE,
4883                                             PCI_DMA_FROMDEVICE);
4884
4885                 pkt = (struct ipw_rx_packet *)rxb->skb->data;
4886                 IPW_DEBUG_RX("Packet: type=%02X seq=%02X bits=%02X\n",
4887                              pkt->header.message_type,
4888                              pkt->header.rx_seq_num,
4889                              pkt->header.control_bits);
4890
4891                 switch (pkt->header.message_type) {
4892                 case RX_FRAME_TYPE: /* 802.11 frame */ {
4893                         struct ieee80211_rx_stats stats = {
4894                                 .rssi = pkt->u.frame.rssi_dbm -
4895                                 IPW_RSSI_TO_DBM,
4896                                 .signal = pkt->u.frame.signal,
4897                                 .rate = pkt->u.frame.rate,
4898                                 .mac_time = jiffies,
4899                                 .received_channel =
4900                                 pkt->u.frame.received_channel,
4901                                 .freq = (pkt->u.frame.control & (1<<0)) ?
4902                                 IEEE80211_24GHZ_BAND : IEEE80211_52GHZ_BAND,
4903                                 .len = pkt->u.frame.length,
4904                         };
4905
4906                         if (stats.rssi != 0)
4907                                 stats.mask |= IEEE80211_STATMASK_RSSI;
4908                         if (stats.signal != 0)
4909                                 stats.mask |= IEEE80211_STATMASK_SIGNAL;
4910                         if (stats.rate != 0)
4911                                 stats.mask |= IEEE80211_STATMASK_RATE;
4912
4913                         priv->rx_packets++;
4914
4915 #ifdef CONFIG_IPW_PROMISC
4916                         if (priv->ieee->iw_mode == IW_MODE_MONITOR) {
4917                                 ipw_handle_data_packet(priv, rxb, &stats);
4918                                 break;
4919                         }
4920 #endif
4921
4922                         header = (struct ieee80211_hdr *)(rxb->skb->data +
4923                                                           IPW_RX_FRAME_SIZE);
4924                                 /* TODO: Check Ad-Hoc dest/source and make sure
4925                                  * that we are actually parsing these packets
4926                                  * correctly -- we should probably use the
4927                                  * frame control of the packet and disregard
4928                                  * the current iw_mode */
4929                         switch (priv->ieee->iw_mode) {
4930                         case IW_MODE_ADHOC:
4931                                 network_packet =
4932                                         !memcmp(header->addr1,
4933                                                 priv->net_dev->dev_addr,
4934                                                 ETH_ALEN) ||
4935                                         !memcmp(header->addr3,
4936                                                 priv->bssid, ETH_ALEN) ||
4937                                         is_broadcast_ether_addr(header->addr1) ||
4938                                         is_multicast_ether_addr(header->addr1);
4939                                 break;
4940
4941                         case IW_MODE_INFRA:
4942                         default:
4943                                 network_packet =
4944                                         !memcmp(header->addr3,
4945                                                 priv->bssid, ETH_ALEN) ||
4946                                         !memcmp(header->addr1,
4947                                                 priv->net_dev->dev_addr,
4948                                                 ETH_ALEN) ||
4949                                         is_broadcast_ether_addr(header->addr1) ||
4950                                         is_multicast_ether_addr(header->addr1);
4951                                 break;
4952                         }
4953
4954                         if (network_packet && priv->assoc_network) {
4955                                 priv->assoc_network->stats.rssi = stats.rssi;
4956                                 average_add(&priv->average_rssi,
4957                                             stats.rssi);
4958                                 priv->last_rx_rssi = stats.rssi;
4959                         }
4960
4961                         IPW_DEBUG_RX("Frame: len=%u\n", pkt->u.frame.length);
4962
4963                         if (pkt->u.frame.length < frame_hdr_len(header)) {
4964                                 IPW_DEBUG_DROP("Received packet is too small. "
4965                                                "Dropping.\n");
4966                                 priv->ieee->stats.rx_errors++;
4967                                 priv->wstats.discard.misc++;
4968                                 break;
4969                         }
4970
4971                         switch (WLAN_FC_GET_TYPE(header->frame_ctl)) {
4972                         case IEEE80211_FTYPE_MGMT:
4973                                 ieee80211_rx_mgt(priv->ieee, header, &stats);
4974                                 if (priv->ieee->iw_mode == IW_MODE_ADHOC &&
4975                                     ((WLAN_FC_GET_STYPE(header->frame_ctl) ==
4976                                       IEEE80211_STYPE_PROBE_RESP) ||
4977                                      (WLAN_FC_GET_STYPE(header->frame_ctl) ==
4978                                       IEEE80211_STYPE_BEACON)) &&
4979                                     !memcmp(header->addr3, priv->bssid, ETH_ALEN))
4980                                         ipw_add_station(priv, header->addr2);
4981                                 break;
4982
4983                         case IEEE80211_FTYPE_CTL:
4984                                 break;
4985
4986                         case IEEE80211_FTYPE_DATA:
4987                                 if (network_packet)
4988                                         ipw_handle_data_packet(priv, rxb, &stats);
4989                                 else
4990                                         IPW_DEBUG_DROP("Dropping: " MAC_FMT
4991                                                        ", " MAC_FMT ", " MAC_FMT "\n",
4992                                                        MAC_ARG(header->addr1), MAC_ARG(header->addr2),
4993                                                        MAC_ARG(header->addr3));
4994                                 break;
4995                         }
4996                         break;
4997                 }
4998
4999                 case RX_HOST_NOTIFICATION_TYPE: {
5000                         IPW_DEBUG_RX("Notification: subtype=%02X flags=%02X size=%d\n",
5001                                      pkt->u.notification.subtype,
5002                                      pkt->u.notification.flags,
5003                                      pkt->u.notification.size);
5004                         ipw_rx_notification(priv, &pkt->u.notification);
5005                         break;
5006                 }
5007
5008                 default:
5009                         IPW_DEBUG_RX("Bad Rx packet of type %d\n",
5010                                      pkt->header.message_type);
5011                         break;
5012                 }
5013
5014                 /* For now we just don't re-use anything.  We can tweak this
5015                  * later to try and re-use notification packets and SKBs that
5016                  * fail to Rx correctly */
5017                 if (rxb->skb != NULL) {
5018                         dev_kfree_skb_any(rxb->skb);
5019                         rxb->skb = NULL;
5020                 }
5021
5022                 pci_unmap_single(priv->pci_dev, rxb->dma_addr,
5023                                  CX2_RX_BUF_SIZE, PCI_DMA_FROMDEVICE);
5024                 list_add_tail(&rxb->list, &priv->rxq->rx_used);
5025
5026                 i = (i + 1) % RX_QUEUE_SIZE;
5027         }
5028
5029         /* Backtrack one entry */
5030         priv->rxq->processed = (i ? i : RX_QUEUE_SIZE) - 1;
5031
5032         ipw_rx_queue_restock(priv);
5033 }
5034
5035 static void ipw_abort_scan(struct ipw_priv *priv)
5036 {
5037         int err;
5038
5039         if (priv->status & STATUS_SCAN_ABORTING) {
5040                 IPW_DEBUG_HC("Ignoring concurrent scan abort request.\n");
5041                 return;
5042         }
5043         priv->status |= STATUS_SCAN_ABORTING;
5044
5045         err = ipw_send_scan_abort(priv);
5046         if (err)
5047                 IPW_DEBUG_HC("Request to abort scan failed.\n");
5048 }
5049
5050 static int ipw_request_scan(struct ipw_priv *priv)
5051 {
5052         struct ipw_scan_request_ext scan;
5053         int channel_index = 0;
5054         int i, err, scan_type;
5055
5056         if (priv->status & STATUS_EXIT_PENDING) {
5057                 IPW_DEBUG_SCAN("Aborting scan due to device shutdown\n");
5058                 priv->status |= STATUS_SCAN_PENDING;
5059                 return 0;
5060         }
5061
5062         if (priv->status & STATUS_SCANNING) {
5063                 IPW_DEBUG_HC("Concurrent scan requested.  Aborting first.\n");
5064                 priv->status |= STATUS_SCAN_PENDING;
5065                 ipw_abort_scan(priv);
5066                 return 0;
5067         }
5068
5069         if (priv->status & STATUS_SCAN_ABORTING) {
5070                 IPW_DEBUG_HC("Scan request while abort pending.  Queuing.\n");
5071                 priv->status |= STATUS_SCAN_PENDING;
5072                 return 0;
5073         }
5074
5075         if (priv->status & STATUS_RF_KILL_MASK) {
5076                 IPW_DEBUG_HC("Aborting scan due to RF Kill activation\n");
5077                 priv->status |= STATUS_SCAN_PENDING;
5078                 return 0;
5079         }
5080
5081         memset(&scan, 0, sizeof(scan));
5082
5083         scan.dwell_time[IPW_SCAN_ACTIVE_BROADCAST_SCAN] = 20;
5084         scan.dwell_time[IPW_SCAN_ACTIVE_BROADCAST_AND_DIRECT_SCAN] = 20;
5085         scan.dwell_time[IPW_SCAN_PASSIVE_FULL_DWELL_SCAN] = 20;
5086
5087         scan.full_scan_index = ieee80211_get_scans(priv->ieee);
5088         /* If we are roaming, then make this a directed scan for the current
5089          * network.  Otherwise, ensure that every other scan is a fast
5090          * channel hop scan */
5091         if ((priv->status & STATUS_ROAMING) || (
5092                     !(priv->status & STATUS_ASSOCIATED) &&
5093                     (priv->config & CFG_STATIC_ESSID) &&
5094                     (scan.full_scan_index % 2))) {
5095                 err = ipw_send_ssid(priv, priv->essid, priv->essid_len);
5096                 if (err) {
5097                         IPW_DEBUG_HC("Attempt to send SSID command failed.\n");
5098                         return err;
5099                 }
5100
5101                 scan_type = IPW_SCAN_ACTIVE_BROADCAST_AND_DIRECT_SCAN;
5102         } else {
5103                 scan_type = IPW_SCAN_ACTIVE_BROADCAST_SCAN;
5104         }
5105
5106         if (priv->ieee->freq_band & IEEE80211_52GHZ_BAND) {
5107                 int start = channel_index;
5108                 for (i = 0; i < MAX_A_CHANNELS; i++) {
5109                         if (band_a_active_channel[i] == 0)
5110                                 break;
5111                         if ((priv->status & STATUS_ASSOCIATED) &&
5112                             band_a_active_channel[i] == priv->channel)
5113                                 continue;
5114                         channel_index++;
5115                         scan.channels_list[channel_index] =
5116                                 band_a_active_channel[i];
5117                         ipw_set_scan_type(&scan, channel_index, scan_type);
5118                 }
5119
5120                 if (start != channel_index) {
5121                         scan.channels_list[start] = (u8)(IPW_A_MODE << 6) |
5122                                 (channel_index - start);
5123                         channel_index++;
5124                 }
5125         }
5126
5127         if (priv->ieee->freq_band & IEEE80211_24GHZ_BAND) {
5128                 int start = channel_index;
5129                 for (i = 0; i < MAX_B_CHANNELS; i++) {
5130                         if (band_b_active_channel[i] == 0)
5131                                 break;
5132                         if ((priv->status & STATUS_ASSOCIATED) &&
5133                             band_b_active_channel[i] == priv->channel)
5134                                 continue;
5135                         channel_index++;
5136                         scan.channels_list[channel_index] =
5137                                 band_b_active_channel[i];
5138                         ipw_set_scan_type(&scan, channel_index, scan_type);
5139                 }
5140
5141                 if (start != channel_index) {
5142                         scan.channels_list[start] = (u8)(IPW_B_MODE << 6) |
5143                                 (channel_index - start);
5144                 }
5145         }
5146
5147         err = ipw_send_scan_request_ext(priv, &scan);
5148         if (err) {
5149                 IPW_DEBUG_HC("Sending scan command failed: %08X\n",
5150                              err);
5151                 return -EIO;
5152         }
5153
5154         priv->status |= STATUS_SCANNING;
5155         priv->status &= ~STATUS_SCAN_PENDING;
5156
5157         return 0;
5158 }
5159
5160 /*
5161  * This file defines the Wireless Extension handlers.  It does not
5162  * define any methods of hardware manipulation and relies on the
5163  * functions defined in ipw_main to provide the HW interaction.
5164  *
5165  * The exception to this is the use of the ipw_get_ordinal()
5166  * function used to poll the hardware vs. making unecessary calls.
5167  *
5168  */
5169
5170 static int ipw_wx_get_name(struct net_device *dev,
5171                            struct iw_request_info *info,
5172                            union iwreq_data *wrqu, char *extra)
5173 {
5174         struct ipw_priv *priv = ieee80211_priv(dev);
5175         if (!(priv->status & STATUS_ASSOCIATED))
5176                 strcpy(wrqu->name, "unassociated");
5177         else
5178                 snprintf(wrqu->name, IFNAMSIZ, "IEEE 802.11%c",
5179                          ipw_modes[priv->assoc_request.ieee_mode]);
5180         IPW_DEBUG_WX("Name: %s\n", wrqu->name);
5181         return 0;
5182 }
5183
5184 static int ipw_set_channel(struct ipw_priv *priv, u8 channel)
5185 {
5186         if (channel == 0) {
5187                 IPW_DEBUG_INFO("Setting channel to ANY (0)\n");
5188                 priv->config &= ~CFG_STATIC_CHANNEL;
5189                 if (!(priv->status & (STATUS_SCANNING | STATUS_ASSOCIATED |
5190                                       STATUS_ASSOCIATING))) {
5191                         IPW_DEBUG_ASSOC("Attempting to associate with new "
5192                                         "parameters.\n");
5193                         ipw_associate(priv);
5194                 }
5195
5196                 return 0;
5197         }
5198
5199         priv->config |= CFG_STATIC_CHANNEL;
5200
5201         if (priv->channel == channel) {
5202                 IPW_DEBUG_INFO(
5203                         "Request to set channel to current value (%d)\n",
5204                         channel);
5205                 return 0;
5206         }
5207
5208         IPW_DEBUG_INFO("Setting channel to %i\n", (int)channel);
5209         priv->channel = channel;
5210
5211         /* If we are currently associated, or trying to associate
5212          * then see if this is a new channel (causing us to disassociate) */
5213         if (priv->status & (STATUS_ASSOCIATED | STATUS_ASSOCIATING)) {
5214                 IPW_DEBUG_ASSOC("Disassociating due to channel change.\n");
5215                 ipw_disassociate(priv);
5216         } else {
5217                 ipw_associate(priv);
5218         }
5219
5220         return 0;
5221 }
5222
5223 static int ipw_wx_set_freq(struct net_device *dev,
5224                            struct iw_request_info *info,
5225                            union iwreq_data *wrqu, char *extra)
5226 {
5227         struct ipw_priv *priv = ieee80211_priv(dev);
5228         struct iw_freq *fwrq = &wrqu->freq;
5229
5230         /* if setting by freq convert to channel */
5231         if (fwrq->e == 1) {
5232                 if ((fwrq->m >= (int) 2.412e8 &&
5233                      fwrq->m <= (int) 2.487e8)) {
5234                         int f = fwrq->m / 100000;
5235                         int c = 0;
5236
5237                         while ((c < REG_MAX_CHANNEL) &&
5238                                (f != ipw_frequencies[c]))
5239                                 c++;
5240
5241                         /* hack to fall through */
5242                         fwrq->e = 0;
5243                         fwrq->m = c + 1;
5244                 }
5245         }
5246
5247         if (fwrq->e > 0 || fwrq->m > 1000)
5248                 return -EOPNOTSUPP;
5249
5250         IPW_DEBUG_WX("SET Freq/Channel -> %d \n", fwrq->m);
5251         return ipw_set_channel(priv, (u8)fwrq->m);
5252
5253         return 0;
5254 }
5255
5256
5257 static int ipw_wx_get_freq(struct net_device *dev,
5258                            struct iw_request_info *info,
5259                            union iwreq_data *wrqu, char *extra)
5260 {
5261         struct ipw_priv *priv = ieee80211_priv(dev);
5262
5263         wrqu->freq.e = 0;
5264
5265         /* If we are associated, trying to associate, or have a statically
5266          * configured CHANNEL then return that; otherwise return ANY */
5267         if (priv->config & CFG_STATIC_CHANNEL ||
5268             priv->status & (STATUS_ASSOCIATING | STATUS_ASSOCIATED))
5269                 wrqu->freq.m = priv->channel;
5270         else
5271                 wrqu->freq.m = 0;
5272
5273         IPW_DEBUG_WX("GET Freq/Channel -> %d \n", priv->channel);
5274         return 0;
5275 }
5276
5277 static int ipw_wx_set_mode(struct net_device *dev,
5278                            struct iw_request_info *info,
5279                            union iwreq_data *wrqu, char *extra)
5280 {
5281         struct ipw_priv *priv = ieee80211_priv(dev);
5282         int err = 0;
5283
5284         IPW_DEBUG_WX("Set MODE: %d\n", wrqu->mode);
5285
5286         if (wrqu->mode == priv->ieee->iw_mode)
5287                 return 0;
5288
5289         switch (wrqu->mode) {
5290 #ifdef CONFIG_IPW_PROMISC
5291         case IW_MODE_MONITOR:
5292 #endif
5293         case IW_MODE_ADHOC:
5294         case IW_MODE_INFRA:
5295                 break;
5296         case IW_MODE_AUTO:
5297                 wrqu->mode = IW_MODE_INFRA;
5298                 break;
5299         default:
5300                 return -EINVAL;
5301         }
5302
5303 #ifdef CONFIG_IPW_PROMISC
5304         if (priv->ieee->iw_mode == IW_MODE_MONITOR)
5305                 priv->net_dev->type = ARPHRD_ETHER;
5306
5307         if (wrqu->mode == IW_MODE_MONITOR)
5308                 priv->net_dev->type = ARPHRD_IEEE80211;
5309 #endif /* CONFIG_IPW_PROMISC */
5310
5311 #ifdef CONFIG_PM
5312         /* Free the existing firmware and reset the fw_loaded
5313          * flag so ipw_load() will bring in the new firmawre */
5314         if (fw_loaded) {
5315                 fw_loaded = 0;
5316         }
5317
5318         release_firmware(bootfw);
5319         release_firmware(ucode);
5320         release_firmware(firmware);
5321         bootfw = ucode = firmware = NULL;
5322 #endif
5323
5324         priv->ieee->iw_mode = wrqu->mode;
5325         ipw_adapter_restart(priv);
5326
5327         return err;
5328 }
5329
5330 static int ipw_wx_get_mode(struct net_device *dev,
5331                                struct iw_request_info *info,
5332                                union iwreq_data *wrqu, char *extra)
5333 {
5334         struct ipw_priv *priv = ieee80211_priv(dev);
5335
5336         wrqu->mode = priv->ieee->iw_mode;
5337         IPW_DEBUG_WX("Get MODE -> %d\n", wrqu->mode);
5338
5339         return 0;
5340 }
5341
5342
5343 #define DEFAULT_RTS_THRESHOLD     2304U
5344 #define MIN_RTS_THRESHOLD         1U
5345 #define MAX_RTS_THRESHOLD         2304U
5346 #define DEFAULT_BEACON_INTERVAL   100U
5347 #define DEFAULT_SHORT_RETRY_LIMIT 7U
5348 #define DEFAULT_LONG_RETRY_LIMIT  4U
5349
5350 /* Values are in microsecond */
5351 static const s32 timeout_duration[] = {
5352         350000,
5353         250000,
5354         75000,
5355         37000,
5356         25000,
5357 };
5358
5359 static const s32 period_duration[] = {
5360         400000,
5361         700000,
5362         1000000,
5363         1000000,
5364         1000000
5365 };
5366
5367 static int ipw_wx_get_range(struct net_device *dev,
5368                             struct iw_request_info *info,
5369                             union iwreq_data *wrqu, char *extra)
5370 {
5371         struct ipw_priv *priv = ieee80211_priv(dev);
5372         struct iw_range *range = (struct iw_range *)extra;
5373         u16 val;
5374         int i;
5375
5376         wrqu->data.length = sizeof(*range);
5377         memset(range, 0, sizeof(*range));
5378
5379         /* 54Mbs == ~27 Mb/s real (802.11g) */
5380         range->throughput = 27 * 1000 * 1000;
5381
5382         range->max_qual.qual = 100;
5383         /* TODO: Find real max RSSI and stick here */
5384         range->max_qual.level = 0;
5385         range->max_qual.noise = 0;
5386         range->max_qual.updated = 7; /* Updated all three */
5387
5388         range->avg_qual.qual = 70;
5389         /* TODO: Find real 'good' to 'bad' threshol value for RSSI */
5390         range->avg_qual.level = 0; /* FIXME to real average level */
5391         range->avg_qual.noise = 0;
5392         range->avg_qual.updated = 7; /* Updated all three */
5393
5394         range->num_bitrates = min(priv->rates.num_rates, (u8)IW_MAX_BITRATES);
5395
5396         for (i = 0; i < range->num_bitrates; i++)
5397                 range->bitrate[i] = (priv->rates.supported_rates[i] & 0x7F) *
5398                         500000;
5399
5400         range->max_rts = DEFAULT_RTS_THRESHOLD;
5401         range->min_frag = MIN_FRAG_THRESHOLD;
5402         range->max_frag = MAX_FRAG_THRESHOLD;
5403
5404         range->encoding_size[0] = 5;
5405         range->encoding_size[1] = 13;
5406         range->num_encoding_sizes = 2;
5407         range->max_encoding_tokens = WEP_KEYS;
5408
5409         /* Set the Wireless Extension versions */
5410         range->we_version_compiled = WIRELESS_EXT;
5411         range->we_version_source = 16;
5412
5413         range->num_channels = FREQ_COUNT;
5414
5415         val = 0;
5416         for (i = 0; i < FREQ_COUNT; i++) {
5417                 range->freq[val].i = i + 1;
5418                 range->freq[val].m = ipw_frequencies[i] * 100000;
5419                 range->freq[val].e = 1;
5420                 val++;
5421
5422                 if (val == IW_MAX_FREQUENCIES)
5423                         break;
5424         }
5425         range->num_frequency = val;
5426
5427         IPW_DEBUG_WX("GET Range\n");
5428         return 0;
5429 }
5430
5431 static int ipw_wx_set_wap(struct net_device *dev,
5432                           struct iw_request_info *info,
5433                           union iwreq_data *wrqu, char *extra)
5434 {
5435         struct ipw_priv *priv = ieee80211_priv(dev);
5436
5437         static const unsigned char any[] = {
5438                 0xff, 0xff, 0xff, 0xff, 0xff, 0xff
5439         };
5440         static const unsigned char off[] = {
5441                 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
5442         };
5443
5444         if (wrqu->ap_addr.sa_family != ARPHRD_ETHER)
5445                 return -EINVAL;
5446
5447         if (!memcmp(any, wrqu->ap_addr.sa_data, ETH_ALEN) ||
5448             !memcmp(off, wrqu->ap_addr.sa_data, ETH_ALEN)) {
5449                 /* we disable mandatory BSSID association */
5450                 IPW_DEBUG_WX("Setting AP BSSID to ANY\n");
5451                 priv->config &= ~CFG_STATIC_BSSID;
5452                 if (!(priv->status & (STATUS_SCANNING | STATUS_ASSOCIATED |
5453                                       STATUS_ASSOCIATING))) {
5454                         IPW_DEBUG_ASSOC("Attempting to associate with new "
5455                                         "parameters.\n");
5456                         ipw_associate(priv);
5457                 }
5458
5459                 return 0;
5460         }
5461
5462         priv->config |= CFG_STATIC_BSSID;
5463         if (!memcmp(priv->bssid, wrqu->ap_addr.sa_data, ETH_ALEN)) {
5464                 IPW_DEBUG_WX("BSSID set to current BSSID.\n");
5465                 return 0;
5466         }
5467
5468         IPW_DEBUG_WX("Setting mandatory BSSID to " MAC_FMT "\n",
5469                      MAC_ARG(wrqu->ap_addr.sa_data));
5470
5471         memcpy(priv->bssid, wrqu->ap_addr.sa_data, ETH_ALEN);
5472
5473         /* If we are currently associated, or trying to associate
5474          * then see if this is a new BSSID (causing us to disassociate) */
5475         if (priv->status & (STATUS_ASSOCIATED | STATUS_ASSOCIATING)) {
5476                 IPW_DEBUG_ASSOC("Disassociating due to BSSID change.\n");
5477                 ipw_disassociate(priv);
5478         } else {
5479                 ipw_associate(priv);
5480         }
5481
5482         return 0;
5483 }
5484
5485 static int ipw_wx_get_wap(struct net_device *dev,
5486                           struct iw_request_info *info,
5487                           union iwreq_data *wrqu, char *extra)
5488 {
5489         struct ipw_priv *priv = ieee80211_priv(dev);
5490         /* If we are associated, trying to associate, or have a statically
5491          * configured BSSID then return that; otherwise return ANY */
5492         if (priv->config & CFG_STATIC_BSSID ||
5493             priv->status & (STATUS_ASSOCIATED | STATUS_ASSOCIATING)) {
5494                 wrqu->ap_addr.sa_family = ARPHRD_ETHER;
5495                 memcpy(wrqu->ap_addr.sa_data, &priv->bssid, ETH_ALEN);
5496         } else
5497                 memset(wrqu->ap_addr.sa_data, 0, ETH_ALEN);
5498
5499         IPW_DEBUG_WX("Getting WAP BSSID: " MAC_FMT "\n",
5500                      MAC_ARG(wrqu->ap_addr.sa_data));
5501         return 0;
5502 }
5503
5504 static int ipw_wx_set_essid(struct net_device *dev,
5505                             struct iw_request_info *info,
5506                             union iwreq_data *wrqu, char *extra)
5507 {
5508         struct ipw_priv *priv = ieee80211_priv(dev);
5509         char *essid = ""; /* ANY */
5510         int length = 0;
5511
5512         if (wrqu->essid.flags && wrqu->essid.length) {
5513                 length = wrqu->essid.length - 1;
5514                 essid = extra;
5515         }
5516         if (length == 0) {
5517                 IPW_DEBUG_WX("Setting ESSID to ANY\n");
5518                 priv->config &= ~CFG_STATIC_ESSID;
5519                 if (!(priv->status & (STATUS_SCANNING | STATUS_ASSOCIATED |
5520                                       STATUS_ASSOCIATING))) {
5521                         IPW_DEBUG_ASSOC("Attempting to associate with new "
5522                                         "parameters.\n");
5523                         ipw_associate(priv);
5524                 }
5525
5526                 return 0;
5527         }
5528
5529         length = min(length, IW_ESSID_MAX_SIZE);
5530
5531         priv->config |= CFG_STATIC_ESSID;
5532
5533         if (priv->essid_len == length && !memcmp(priv->essid, extra, length)) {
5534                 IPW_DEBUG_WX("ESSID set to current ESSID.\n");
5535                 return 0;
5536         }
5537
5538         IPW_DEBUG_WX("Setting ESSID: '%s' (%d)\n", escape_essid(essid, length),
5539                      length);
5540
5541         priv->essid_len = length;
5542         memcpy(priv->essid, essid, priv->essid_len);
5543
5544         /* If we are currently associated, or trying to associate
5545          * then see if this is a new ESSID (causing us to disassociate) */
5546         if (priv->status & (STATUS_ASSOCIATED | STATUS_ASSOCIATING)) {
5547                 IPW_DEBUG_ASSOC("Disassociating due to ESSID change.\n");
5548                 ipw_disassociate(priv);
5549         } else {
5550                 ipw_associate(priv);
5551         }
5552
5553         return 0;
5554 }
5555
5556 static int ipw_wx_get_essid(struct net_device *dev,
5557                             struct iw_request_info *info,
5558                             union iwreq_data *wrqu, char *extra)
5559 {
5560         struct ipw_priv *priv = ieee80211_priv(dev);
5561
5562         /* If we are associated, trying to associate, or have a statically
5563          * configured ESSID then return that; otherwise return ANY */
5564         if (priv->config & CFG_STATIC_ESSID ||
5565             priv->status & (STATUS_ASSOCIATED | STATUS_ASSOCIATING)) {
5566                 IPW_DEBUG_WX("Getting essid: '%s'\n",
5567                              escape_essid(priv->essid, priv->essid_len));
5568                 memcpy(extra, priv->essid, priv->essid_len);
5569                 wrqu->essid.length = priv->essid_len;
5570                 wrqu->essid.flags = 1; /* active */
5571         } else {
5572                 IPW_DEBUG_WX("Getting essid: ANY\n");
5573                 wrqu->essid.length = 0;
5574                 wrqu->essid.flags = 0; /* active */
5575         }
5576
5577         return 0;
5578 }
5579
5580 static int ipw_wx_set_nick(struct net_device *dev,
5581                            struct iw_request_info *info,
5582                            union iwreq_data *wrqu, char *extra)
5583 {
5584         struct ipw_priv *priv = ieee80211_priv(dev);
5585
5586         IPW_DEBUG_WX("Setting nick to '%s'\n", extra);
5587         if (wrqu->data.length > IW_ESSID_MAX_SIZE)
5588                 return -E2BIG;
5589
5590         wrqu->data.length = min((size_t)wrqu->data.length, sizeof(priv->nick));
5591         memset(priv->nick, 0, sizeof(priv->nick));
5592         memcpy(priv->nick, extra,  wrqu->data.length);
5593         IPW_DEBUG_TRACE("<<\n");
5594         return 0;
5595
5596 }
5597
5598
5599 static int ipw_wx_get_nick(struct net_device *dev,
5600                            struct iw_request_info *info,
5601                            union iwreq_data *wrqu, char *extra)
5602 {
5603         struct ipw_priv *priv = ieee80211_priv(dev);
5604         IPW_DEBUG_WX("Getting nick\n");
5605         wrqu->data.length = strlen(priv->nick) + 1;
5606         memcpy(extra, priv->nick, wrqu->data.length);
5607         wrqu->data.flags = 1; /* active */
5608         return 0;
5609 }
5610
5611
5612 static int ipw_wx_set_rate(struct net_device *dev,
5613                            struct iw_request_info *info,
5614                            union iwreq_data *wrqu, char *extra)
5615 {
5616         IPW_DEBUG_WX("0x%p, 0x%p, 0x%p\n", dev, info, wrqu);
5617         return -EOPNOTSUPP;
5618 }
5619
5620 static int ipw_wx_get_rate(struct net_device *dev,
5621                            struct iw_request_info *info,
5622                            union iwreq_data *wrqu, char *extra)
5623 {
5624         struct ipw_priv * priv = ieee80211_priv(dev);
5625         wrqu->bitrate.value = priv->last_rate;
5626
5627         IPW_DEBUG_WX("GET Rate -> %d \n", wrqu->bitrate.value);
5628         return 0;
5629 }
5630
5631
5632 static int ipw_wx_set_rts(struct net_device *dev,
5633                           struct iw_request_info *info,
5634                           union iwreq_data *wrqu, char *extra)
5635 {
5636         struct ipw_priv *priv = ieee80211_priv(dev);
5637
5638         if (wrqu->rts.disabled)
5639                 priv->rts_threshold = DEFAULT_RTS_THRESHOLD;
5640         else {
5641                 if (wrqu->rts.value < MIN_RTS_THRESHOLD ||
5642                     wrqu->rts.value > MAX_RTS_THRESHOLD)
5643                         return -EINVAL;
5644
5645                 priv->rts_threshold = wrqu->rts.value;
5646         }
5647
5648         ipw_send_rts_threshold(priv, priv->rts_threshold);
5649         IPW_DEBUG_WX("SET RTS Threshold -> %d \n", priv->rts_threshold);
5650         return 0;
5651 }
5652
5653 static int ipw_wx_get_rts(struct net_device *dev,
5654                           struct iw_request_info *info,
5655                           union iwreq_data *wrqu, char *extra)
5656 {
5657         struct ipw_priv *priv = ieee80211_priv(dev);
5658         wrqu->rts.value = priv->rts_threshold;
5659         wrqu->rts.fixed = 0;    /* no auto select */
5660         wrqu->rts.disabled =
5661                 (wrqu->rts.value == DEFAULT_RTS_THRESHOLD);
5662
5663         IPW_DEBUG_WX("GET RTS Threshold -> %d \n", wrqu->rts.value);
5664         return 0;
5665 }
5666
5667
5668 static int ipw_wx_set_txpow(struct net_device *dev,
5669                             struct iw_request_info *info,
5670                             union iwreq_data *wrqu, char *extra)
5671 {
5672         struct ipw_priv *priv = ieee80211_priv(dev);
5673         struct ipw_tx_power tx_power;
5674         int i;
5675
5676         if (ipw_radio_kill_sw(priv, wrqu->power.disabled))
5677                 return -EINPROGRESS;
5678
5679         if (wrqu->power.flags != IW_TXPOW_DBM)
5680                 return -EINVAL;
5681
5682         if ((wrqu->power.value > 20) ||
5683             (wrqu->power.value < -12))
5684                 return -EINVAL;
5685
5686         priv->tx_power = wrqu->power.value;
5687
5688         memset(&tx_power, 0, sizeof(tx_power));
5689
5690         /* configure device for 'G' band */
5691         tx_power.ieee_mode = IPW_G_MODE;
5692         tx_power.num_channels = 11;
5693         for (i = 0; i < 11; i++) {
5694                 tx_power.channels_tx_power[i].channel_number = i + 1;
5695                 tx_power.channels_tx_power[i].tx_power = priv->tx_power;
5696         }
5697         if (ipw_send_tx_power(priv, &tx_power))
5698                 goto error;
5699
5700         /* configure device to also handle 'B' band */
5701         tx_power.ieee_mode = IPW_B_MODE;
5702         if (ipw_send_tx_power(priv, &tx_power))
5703                 goto error;
5704
5705         return 0;
5706
5707  error:
5708         return -EIO;
5709 }
5710
5711
5712 static int ipw_wx_get_txpow(struct net_device *dev,
5713                             struct iw_request_info *info,
5714                             union iwreq_data *wrqu, char *extra)
5715 {
5716         struct ipw_priv *priv = ieee80211_priv(dev);
5717
5718         wrqu->power.value = priv->tx_power;
5719         wrqu->power.fixed = 1;
5720         wrqu->power.flags = IW_TXPOW_DBM;
5721         wrqu->power.disabled = (priv->status & STATUS_RF_KILL_MASK) ? 1 : 0;
5722
5723         IPW_DEBUG_WX("GET TX Power -> %s %d \n",
5724                      wrqu->power.disabled ? "ON" : "OFF",
5725                      wrqu->power.value);
5726
5727         return 0;
5728 }
5729
5730 static int ipw_wx_set_frag(struct net_device *dev,
5731                                struct iw_request_info *info,
5732                                union iwreq_data *wrqu, char *extra)
5733 {
5734         struct ipw_priv *priv = ieee80211_priv(dev);
5735
5736         if (wrqu->frag.disabled)
5737                 priv->ieee->fts = DEFAULT_FTS;
5738         else {
5739                 if (wrqu->frag.value < MIN_FRAG_THRESHOLD ||
5740                     wrqu->frag.value > MAX_FRAG_THRESHOLD)
5741                         return -EINVAL;
5742
5743                 priv->ieee->fts = wrqu->frag.value & ~0x1;
5744         }
5745
5746         ipw_send_frag_threshold(priv, wrqu->frag.value);
5747         IPW_DEBUG_WX("SET Frag Threshold -> %d \n", wrqu->frag.value);
5748         return 0;
5749 }
5750
5751 static int ipw_wx_get_frag(struct net_device *dev,
5752                                struct iw_request_info *info,
5753                                union iwreq_data *wrqu, char *extra)
5754 {
5755         struct ipw_priv *priv = ieee80211_priv(dev);
5756         wrqu->frag.value = priv->ieee->fts;
5757         wrqu->frag.fixed = 0;   /* no auto select */
5758         wrqu->frag.disabled =
5759                 (wrqu->frag.value == DEFAULT_FTS);
5760
5761         IPW_DEBUG_WX("GET Frag Threshold -> %d \n", wrqu->frag.value);
5762
5763         return 0;
5764 }
5765
5766 static int ipw_wx_set_retry(struct net_device *dev,
5767                             struct iw_request_info *info,
5768                             union iwreq_data *wrqu, char *extra)
5769 {
5770         IPW_DEBUG_WX("0x%p, 0x%p, 0x%p\n", dev, info, wrqu);
5771         return -EOPNOTSUPP;
5772 }
5773
5774
5775 static int ipw_wx_get_retry(struct net_device *dev,
5776                             struct iw_request_info *info,
5777                             union iwreq_data *wrqu, char *extra)
5778 {
5779         IPW_DEBUG_WX("0x%p, 0x%p, 0x%p\n", dev, info, wrqu);
5780         return -EOPNOTSUPP;
5781 }
5782
5783
5784 static int ipw_wx_set_scan(struct net_device *dev,
5785                            struct iw_request_info *info,
5786                            union iwreq_data *wrqu, char *extra)
5787 {
5788         struct ipw_priv *priv = ieee80211_priv(dev);
5789         IPW_DEBUG_WX("Start scan\n");
5790         if (ipw_request_scan(priv))
5791                 return -EIO;
5792         return 0;
5793 }
5794
5795 static int ipw_wx_get_scan(struct net_device *dev,
5796                            struct iw_request_info *info,
5797                            union iwreq_data *wrqu, char *extra)
5798 {
5799         struct ipw_priv *priv = ieee80211_priv(dev);
5800         return ieee80211_wx_get_scan(priv->ieee, info, wrqu, extra);
5801 }
5802
5803 static int ipw_wx_set_encode(struct net_device *dev,
5804                                  struct iw_request_info *info,
5805                                  union iwreq_data *wrqu, char *key)
5806 {
5807         struct ipw_priv *priv = ieee80211_priv(dev);
5808         return ieee80211_wx_set_encode(priv->ieee, info, wrqu, key);
5809 }
5810
5811 static int ipw_wx_get_encode(struct net_device *dev,
5812                                  struct iw_request_info *info,
5813                                  union iwreq_data *wrqu, char *key)
5814 {
5815         struct ipw_priv *priv = ieee80211_priv(dev);
5816         return ieee80211_wx_get_encode(priv->ieee, info, wrqu, key);
5817 }
5818
5819 static int ipw_wx_set_power(struct net_device *dev,
5820                                 struct iw_request_info *info,
5821                                 union iwreq_data *wrqu, char *extra)
5822 {
5823         struct ipw_priv *priv = ieee80211_priv(dev);
5824         int err;
5825
5826         if (wrqu->power.disabled) {
5827                 priv->power_mode = IPW_POWER_LEVEL(priv->power_mode);
5828                 err = ipw_send_power_mode(priv, IPW_POWER_MODE_CAM);
5829                 if (err) {
5830                         IPW_DEBUG_WX("failed setting power mode.\n");
5831                         return err;
5832                 }
5833
5834                 IPW_DEBUG_WX("SET Power Management Mode -> off\n");
5835
5836                 return 0;
5837         }
5838
5839         switch (wrqu->power.flags & IW_POWER_MODE) {
5840         case IW_POWER_ON:    /* If not specified */
5841         case IW_POWER_MODE:  /* If set all mask */
5842         case IW_POWER_ALL_R: /* If explicitely state all */
5843                 break;
5844         default: /* Otherwise we don't support it */
5845                 IPW_DEBUG_WX("SET PM Mode: %X not supported.\n",
5846                              wrqu->power.flags);
5847                 return -EOPNOTSUPP;
5848         }
5849
5850         /* If the user hasn't specified a power management mode yet, default
5851          * to BATTERY */
5852         if (IPW_POWER_LEVEL(priv->power_mode) == IPW_POWER_AC)
5853                 priv->power_mode = IPW_POWER_ENABLED | IPW_POWER_BATTERY;
5854         else
5855                 priv->power_mode = IPW_POWER_ENABLED | priv->power_mode;
5856         err = ipw_send_power_mode(priv, IPW_POWER_LEVEL(priv->power_mode));
5857         if (err) {
5858                 IPW_DEBUG_WX("failed setting power mode.\n");
5859                 return err;
5860         }
5861
5862         IPW_DEBUG_WX("SET Power Management Mode -> 0x%02X\n",
5863                      priv->power_mode);
5864
5865         return 0;
5866 }
5867
5868 static int ipw_wx_get_power(struct net_device *dev,
5869                                 struct iw_request_info *info,
5870                                 union iwreq_data *wrqu, char *extra)
5871 {
5872         struct ipw_priv *priv = ieee80211_priv(dev);
5873
5874         if (!(priv->power_mode & IPW_POWER_ENABLED)) {
5875                 wrqu->power.disabled = 1;
5876         } else {
5877                 wrqu->power.disabled = 0;
5878         }
5879
5880         IPW_DEBUG_WX("GET Power Management Mode -> %02X\n", priv->power_mode);
5881
5882         return 0;
5883 }
5884
5885 static int ipw_wx_set_powermode(struct net_device *dev,
5886                                     struct iw_request_info *info,
5887                                     union iwreq_data *wrqu, char *extra)
5888 {
5889         struct ipw_priv *priv = ieee80211_priv(dev);
5890         int mode = *(int *)extra;
5891         int err;
5892
5893         if ((mode < 1) || (mode > IPW_POWER_LIMIT)) {
5894                 mode = IPW_POWER_AC;
5895                 priv->power_mode = mode;
5896         } else {
5897                 priv->power_mode = IPW_POWER_ENABLED | mode;
5898         }
5899
5900         if (priv->power_mode != mode) {
5901                 err = ipw_send_power_mode(priv, mode);
5902
5903                 if (err) {
5904                         IPW_DEBUG_WX("failed setting power mode.\n");
5905                         return err;
5906                 }
5907         }
5908
5909         return 0;
5910 }
5911
5912 #define MAX_WX_STRING 80
5913 static int ipw_wx_get_powermode(struct net_device *dev,
5914                                     struct iw_request_info *info,
5915                                     union iwreq_data *wrqu, char *extra)
5916 {
5917         struct ipw_priv *priv = ieee80211_priv(dev);
5918         int level = IPW_POWER_LEVEL(priv->power_mode);
5919         char *p = extra;
5920
5921         p += snprintf(p, MAX_WX_STRING, "Power save level: %d ", level);
5922
5923         switch (level) {
5924         case IPW_POWER_AC:
5925                 p += snprintf(p, MAX_WX_STRING - (p - extra), "(AC)");
5926                 break;
5927         case IPW_POWER_BATTERY:
5928                 p += snprintf(p, MAX_WX_STRING - (p - extra), "(BATTERY)");
5929                 break;
5930         default:
5931                 p += snprintf(p, MAX_WX_STRING - (p - extra),
5932                               "(Timeout %dms, Period %dms)",
5933                               timeout_duration[level - 1] / 1000,
5934                               period_duration[level - 1] / 1000);
5935         }
5936
5937         if (!(priv->power_mode & IPW_POWER_ENABLED))
5938                 p += snprintf(p, MAX_WX_STRING - (p - extra)," OFF");
5939
5940         wrqu->data.length = p - extra + 1;
5941
5942         return 0;
5943 }
5944
5945 static int ipw_wx_set_wireless_mode(struct net_device *dev,
5946                                     struct iw_request_info *info,
5947                                     union iwreq_data *wrqu, char *extra)
5948 {
5949         struct ipw_priv *priv = ieee80211_priv(dev);
5950         int mode = *(int *)extra;
5951         u8 band = 0, modulation = 0;
5952
5953         if (mode == 0 || mode & ~IEEE_MODE_MASK) {
5954                 IPW_WARNING("Attempt to set invalid wireless mode: %d\n",
5955                             mode);
5956                 return -EINVAL;
5957         }
5958
5959         if (priv->adapter == IPW_2915ABG) {
5960                 priv->ieee->abg_ture = 1;
5961                 if (mode & IEEE_A) {
5962                         band |= IEEE80211_52GHZ_BAND;
5963                         modulation |= IEEE80211_OFDM_MODULATION;
5964                 } else
5965                         priv->ieee->abg_ture = 0;
5966         } else {
5967                 if (mode & IEEE_A) {
5968                         IPW_WARNING("Attempt to set 2200BG into "
5969                                     "802.11a mode\n");
5970                         return -EINVAL;
5971                 }
5972
5973                 priv->ieee->abg_ture = 0;
5974         }
5975
5976         if (mode & IEEE_B) {
5977                 band |= IEEE80211_24GHZ_BAND;
5978                 modulation |= IEEE80211_CCK_MODULATION;
5979         } else
5980                 priv->ieee->abg_ture = 0;
5981
5982         if (mode & IEEE_G) {
5983                 band |= IEEE80211_24GHZ_BAND;
5984                 modulation |= IEEE80211_OFDM_MODULATION;
5985         } else
5986                 priv->ieee->abg_ture = 0;
5987
5988         priv->ieee->mode = mode;
5989         priv->ieee->freq_band = band;
5990         priv->ieee->modulation = modulation;
5991         init_supported_rates(priv, &priv->rates);
5992
5993         /* If we are currently associated, or trying to associate
5994          * then see if this is a new configuration (causing us to
5995          * disassociate) */
5996         if (priv->status & (STATUS_ASSOCIATED | STATUS_ASSOCIATING)) {
5997                 /* The resulting association will trigger
5998                  * the new rates to be sent to the device */
5999                 IPW_DEBUG_ASSOC("Disassociating due to mode change.\n");
6000                 ipw_disassociate(priv);
6001         } else
6002                 ipw_send_supported_rates(priv, &priv->rates);
6003
6004         IPW_DEBUG_WX("PRIV SET MODE: %c%c%c\n",
6005                      mode & IEEE_A ? 'a' : '.',
6006                      mode & IEEE_B ? 'b' : '.',
6007                      mode & IEEE_G ? 'g' : '.');
6008         return 0;
6009 }
6010
6011 static int ipw_wx_get_wireless_mode(struct net_device *dev,
6012                                     struct iw_request_info *info,
6013                                     union iwreq_data *wrqu, char *extra)
6014 {
6015         struct ipw_priv *priv = ieee80211_priv(dev);
6016
6017         switch (priv->ieee->freq_band) {
6018         case IEEE80211_24GHZ_BAND:
6019                 switch (priv->ieee->modulation) {
6020                 case IEEE80211_CCK_MODULATION:
6021                         strncpy(extra, "802.11b (2)", MAX_WX_STRING);
6022                         break;
6023                 case IEEE80211_OFDM_MODULATION:
6024                         strncpy(extra, "802.11g (4)", MAX_WX_STRING);
6025                         break;
6026                 default:
6027                         strncpy(extra, "802.11bg (6)", MAX_WX_STRING);
6028                         break;
6029                 }
6030                 break;
6031
6032         case IEEE80211_52GHZ_BAND:
6033                 strncpy(extra, "802.11a (1)", MAX_WX_STRING);
6034                 break;
6035
6036         default: /* Mixed Band */
6037                 switch (priv->ieee->modulation) {
6038                 case IEEE80211_CCK_MODULATION:
6039                         strncpy(extra, "802.11ab (3)", MAX_WX_STRING);
6040                         break;
6041                 case IEEE80211_OFDM_MODULATION:
6042                         strncpy(extra, "802.11ag (5)", MAX_WX_STRING);
6043                         break;
6044                 default:
6045                         strncpy(extra, "802.11abg (7)", MAX_WX_STRING);
6046                         break;
6047                 }
6048                 break;
6049         }
6050
6051         IPW_DEBUG_WX("PRIV GET MODE: %s\n", extra);
6052
6053         wrqu->data.length = strlen(extra) + 1;
6054
6055         return 0;
6056 }
6057
6058 #ifdef CONFIG_IPW_PROMISC
6059 static int ipw_wx_set_promisc(struct net_device *dev,
6060                               struct iw_request_info *info,
6061                               union iwreq_data *wrqu, char *extra)
6062 {
6063         struct ipw_priv *priv = ieee80211_priv(dev);
6064         int *parms = (int *)extra;
6065         int enable = (parms[0] > 0);
6066
6067         IPW_DEBUG_WX("SET PROMISC: %d %d\n", enable, parms[1]);
6068         if (enable) {
6069                 if (priv->ieee->iw_mode != IW_MODE_MONITOR) {
6070                         priv->net_dev->type = ARPHRD_IEEE80211;
6071                         ipw_adapter_restart(priv);
6072                 }
6073
6074                 ipw_set_channel(priv, parms[1]);
6075         } else {
6076                 if (priv->ieee->iw_mode != IW_MODE_MONITOR)
6077                         return 0;
6078                 priv->net_dev->type = ARPHRD_ETHER;
6079                 ipw_adapter_restart(priv);
6080         }
6081         return 0;
6082 }
6083
6084
6085 static int ipw_wx_reset(struct net_device *dev,
6086                         struct iw_request_info *info,
6087                         union iwreq_data *wrqu, char *extra)
6088 {
6089         struct ipw_priv *priv = ieee80211_priv(dev);
6090         IPW_DEBUG_WX("RESET\n");
6091         ipw_adapter_restart(priv);
6092         return 0;
6093 }
6094 #endif // CONFIG_IPW_PROMISC
6095
6096 /* Rebase the WE IOCTLs to zero for the handler array */
6097 #define IW_IOCTL(x) [(x)-SIOCSIWCOMMIT]
6098 static iw_handler ipw_wx_handlers[] =
6099 {
6100         IW_IOCTL(SIOCGIWNAME)   = ipw_wx_get_name,
6101         IW_IOCTL(SIOCSIWFREQ)   = ipw_wx_set_freq,
6102         IW_IOCTL(SIOCGIWFREQ)   = ipw_wx_get_freq,
6103         IW_IOCTL(SIOCSIWMODE)   = ipw_wx_set_mode,
6104         IW_IOCTL(SIOCGIWMODE)   = ipw_wx_get_mode,
6105         IW_IOCTL(SIOCGIWRANGE)  = ipw_wx_get_range,
6106         IW_IOCTL(SIOCSIWAP)     = ipw_wx_set_wap,
6107         IW_IOCTL(SIOCGIWAP)     = ipw_wx_get_wap,
6108         IW_IOCTL(SIOCSIWSCAN)   = ipw_wx_set_scan,
6109         IW_IOCTL(SIOCGIWSCAN)   = ipw_wx_get_scan,
6110         IW_IOCTL(SIOCSIWESSID)  = ipw_wx_set_essid,
6111         IW_IOCTL(SIOCGIWESSID)  = ipw_wx_get_essid,
6112         IW_IOCTL(SIOCSIWNICKN)  = ipw_wx_set_nick,
6113         IW_IOCTL(SIOCGIWNICKN)  = ipw_wx_get_nick,
6114         IW_IOCTL(SIOCSIWRATE)   = ipw_wx_set_rate,
6115         IW_IOCTL(SIOCGIWRATE)   = ipw_wx_get_rate,
6116         IW_IOCTL(SIOCSIWRTS)    = ipw_wx_set_rts,
6117         IW_IOCTL(SIOCGIWRTS)    = ipw_wx_get_rts,
6118         IW_IOCTL(SIOCSIWFRAG)   = ipw_wx_set_frag,
6119         IW_IOCTL(SIOCGIWFRAG)   = ipw_wx_get_frag,
6120         IW_IOCTL(SIOCSIWTXPOW)  = ipw_wx_set_txpow,
6121         IW_IOCTL(SIOCGIWTXPOW)  = ipw_wx_get_txpow,
6122         IW_IOCTL(SIOCSIWRETRY)  = ipw_wx_set_retry,
6123         IW_IOCTL(SIOCGIWRETRY)  = ipw_wx_get_retry,
6124         IW_IOCTL(SIOCSIWENCODE) = ipw_wx_set_encode,
6125         IW_IOCTL(SIOCGIWENCODE) = ipw_wx_get_encode,
6126         IW_IOCTL(SIOCSIWPOWER)  = ipw_wx_set_power,
6127         IW_IOCTL(SIOCGIWPOWER)  = ipw_wx_get_power,
6128 };
6129
6130 #define IPW_PRIV_SET_POWER      SIOCIWFIRSTPRIV
6131 #define IPW_PRIV_GET_POWER      SIOCIWFIRSTPRIV+1
6132 #define IPW_PRIV_SET_MODE       SIOCIWFIRSTPRIV+2
6133 #define IPW_PRIV_GET_MODE       SIOCIWFIRSTPRIV+3
6134 #define IPW_PRIV_SET_PROMISC    SIOCIWFIRSTPRIV+4
6135 #define IPW_PRIV_RESET          SIOCIWFIRSTPRIV+5
6136
6137
6138 static struct iw_priv_args ipw_priv_args[] = {
6139         {
6140                 .cmd = IPW_PRIV_SET_POWER,
6141                 .set_args = IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1,
6142                 .name = "set_power"
6143         },
6144         {
6145                 .cmd = IPW_PRIV_GET_POWER,
6146                 .get_args = IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_FIXED | MAX_WX_STRING,
6147                 .name = "get_power"
6148         },
6149         {
6150                 .cmd = IPW_PRIV_SET_MODE,
6151                 .set_args = IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1,
6152                 .name = "set_mode"
6153         },
6154         {
6155                 .cmd = IPW_PRIV_GET_MODE,
6156                 .get_args = IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_FIXED | MAX_WX_STRING,
6157                 .name = "get_mode"
6158         },
6159 #ifdef CONFIG_IPW_PROMISC
6160         {
6161                 IPW_PRIV_SET_PROMISC,
6162                 IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 2, 0, "monitor"
6163         },
6164         {
6165                 IPW_PRIV_RESET,
6166                 IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 0, 0, "reset"
6167         },
6168 #endif /* CONFIG_IPW_PROMISC */
6169 };
6170
6171 static iw_handler ipw_priv_handler[] = {
6172         ipw_wx_set_powermode,
6173         ipw_wx_get_powermode,
6174         ipw_wx_set_wireless_mode,
6175         ipw_wx_get_wireless_mode,
6176 #ifdef CONFIG_IPW_PROMISC
6177         ipw_wx_set_promisc,
6178         ipw_wx_reset,
6179 #endif
6180 };
6181
6182 static struct iw_handler_def ipw_wx_handler_def =
6183 {
6184         .standard       = ipw_wx_handlers,
6185         .num_standard   = ARRAY_SIZE(ipw_wx_handlers),
6186         .num_private    = ARRAY_SIZE(ipw_priv_handler),
6187         .num_private_args = ARRAY_SIZE(ipw_priv_args),
6188         .private        = ipw_priv_handler,
6189         .private_args   = ipw_priv_args,
6190 };
6191
6192
6193
6194
6195 /*
6196  * Get wireless statistics.
6197  * Called by /proc/net/wireless
6198  * Also called by SIOCGIWSTATS
6199  */
6200 static struct iw_statistics *ipw_get_wireless_stats(struct net_device * dev)
6201 {
6202         struct ipw_priv *priv = ieee80211_priv(dev);
6203         struct iw_statistics *wstats;
6204
6205         wstats = &priv->wstats;
6206
6207         /* if hw is disabled, then ipw2100_get_ordinal() can't be called.
6208          * ipw2100_wx_wireless_stats seems to be called before fw is
6209          * initialized.  STATUS_ASSOCIATED will only be set if the hw is up
6210          * and associated; if not associcated, the values are all meaningless
6211          * anyway, so set them all to NULL and INVALID */
6212         if (!(priv->status & STATUS_ASSOCIATED)) {
6213                 wstats->miss.beacon = 0;
6214                 wstats->discard.retries = 0;
6215                 wstats->qual.qual = 0;
6216                 wstats->qual.level = 0;
6217                 wstats->qual.noise = 0;
6218                 wstats->qual.updated = 7;
6219                 wstats->qual.updated |= IW_QUAL_NOISE_INVALID |
6220                         IW_QUAL_QUAL_INVALID | IW_QUAL_LEVEL_INVALID;
6221                 return wstats;
6222         }
6223
6224         wstats->qual.qual = priv->quality;
6225         wstats->qual.level = average_value(&priv->average_rssi);
6226         wstats->qual.noise = average_value(&priv->average_noise);
6227         wstats->qual.updated = IW_QUAL_QUAL_UPDATED | IW_QUAL_LEVEL_UPDATED |
6228                 IW_QUAL_NOISE_UPDATED;
6229
6230         wstats->miss.beacon = average_value(&priv->average_missed_beacons);
6231         wstats->discard.retries = priv->last_tx_failures;
6232         wstats->discard.code = priv->ieee->ieee_stats.rx_discards_undecryptable;
6233
6234 /*      if (ipw_get_ordinal(priv, IPW_ORD_STAT_TX_RETRY, &tx_retry, &len))
6235         goto fail_get_ordinal;
6236         wstats->discard.retries += tx_retry; */
6237
6238         return wstats;
6239 }
6240
6241
6242 /* net device stuff */
6243
6244 static inline void init_sys_config(struct ipw_sys_config *sys_config)
6245 {
6246         memset(sys_config, 0, sizeof(struct ipw_sys_config));
6247         sys_config->bt_coexistence = 1; /* We may need to look into prvStaBtConfig */
6248         sys_config->answer_broadcast_ssid_probe = 0;
6249         sys_config->accept_all_data_frames = 0;
6250         sys_config->accept_non_directed_frames = 1;
6251         sys_config->exclude_unicast_unencrypted = 0;
6252         sys_config->disable_unicast_decryption = 1;
6253         sys_config->exclude_multicast_unencrypted = 0;
6254         sys_config->disable_multicast_decryption = 1;
6255         sys_config->antenna_diversity = CFG_SYS_ANTENNA_BOTH;
6256         sys_config->pass_crc_to_host = 0; /* TODO: See if 1 gives us FCS */
6257         sys_config->dot11g_auto_detection = 0;
6258         sys_config->enable_cts_to_self = 0;
6259         sys_config->bt_coexist_collision_thr = 0;
6260         sys_config->pass_noise_stats_to_host = 1;
6261 }
6262
6263 static int ipw_net_open(struct net_device *dev)
6264 {
6265         struct ipw_priv *priv = ieee80211_priv(dev);
6266         IPW_DEBUG_INFO("dev->open\n");
6267         /* we should be verifying the device is ready to be opened */
6268         if (!(priv->status & STATUS_RF_KILL_MASK) &&
6269             (priv->status & STATUS_ASSOCIATED))
6270                 netif_start_queue(dev);
6271         return 0;
6272 }
6273
6274 static int ipw_net_stop(struct net_device *dev)
6275 {
6276         IPW_DEBUG_INFO("dev->close\n");
6277         netif_stop_queue(dev);
6278         return 0;
6279 }
6280
6281 /*
6282 todo:
6283
6284 modify to send one tfd per fragment instead of using chunking.  otherwise
6285 we need to heavily modify the ieee80211_skb_to_txb.
6286 */
6287
6288 static inline void ipw_tx_skb(struct ipw_priv *priv, struct ieee80211_txb *txb)
6289 {
6290         struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)
6291                 txb->fragments[0]->data;
6292         int i = 0;
6293         struct tfd_frame *tfd;
6294         struct clx2_tx_queue *txq = &priv->txq[0];
6295         struct clx2_queue *q = &txq->q;
6296         u8 id, hdr_len, unicast;
6297         u16 remaining_bytes;
6298
6299         switch (priv->ieee->iw_mode) {
6300         case IW_MODE_ADHOC:
6301                 hdr_len = IEEE80211_3ADDR_LEN;
6302                 unicast = !is_broadcast_ether_addr(hdr->addr1) &&
6303                         !is_multicast_ether_addr(hdr->addr1);
6304                 id = ipw_find_station(priv, hdr->addr1);
6305                 if (id == IPW_INVALID_STATION) {
6306                         id = ipw_add_station(priv, hdr->addr1);
6307                         if (id == IPW_INVALID_STATION) {
6308                                 IPW_WARNING("Attempt to send data to "
6309                                             "invalid cell: " MAC_FMT "\n",
6310                                             MAC_ARG(hdr->addr1));
6311                                 goto drop;
6312                         }
6313                 }
6314                 break;
6315
6316         case IW_MODE_INFRA:
6317         default:
6318                 unicast = !is_broadcast_ether_addr(hdr->addr3) &&
6319                         !is_multicast_ether_addr(hdr->addr3);
6320                 hdr_len = IEEE80211_3ADDR_LEN;
6321                 id = 0;
6322                 break;
6323         }
6324
6325         tfd = &txq->bd[q->first_empty];
6326         txq->txb[q->first_empty] = txb;
6327         memset(tfd, 0, sizeof(*tfd));
6328         tfd->u.data.station_number = id;
6329
6330         tfd->control_flags.message_type = TX_FRAME_TYPE;
6331         tfd->control_flags.control_bits = TFD_NEED_IRQ_MASK;
6332
6333         tfd->u.data.cmd_id = DINO_CMD_TX;
6334         tfd->u.data.len = txb->payload_size;
6335         remaining_bytes = txb->payload_size;
6336         if (unlikely(!unicast))
6337                 tfd->u.data.tx_flags = DCT_FLAG_NO_WEP;
6338         else
6339                 tfd->u.data.tx_flags = DCT_FLAG_NO_WEP | DCT_FLAG_ACK_REQD;
6340
6341         if (priv->assoc_request.ieee_mode == IPW_B_MODE)
6342                 tfd->u.data.tx_flags_ext = DCT_FLAG_EXT_MODE_CCK;
6343         else
6344                 tfd->u.data.tx_flags_ext = DCT_FLAG_EXT_MODE_OFDM;
6345
6346         if (priv->config & CFG_PREAMBLE)
6347                 tfd->u.data.tx_flags |= DCT_FLAG_SHORT_PREMBL;
6348
6349         memcpy(&tfd->u.data.tfd.tfd_24.mchdr, hdr, hdr_len);
6350
6351         /* payload */
6352         tfd->u.data.num_chunks = min((u8)(NUM_TFD_CHUNKS - 2), txb->nr_frags);
6353         for (i = 0; i < tfd->u.data.num_chunks; i++) {
6354                 IPW_DEBUG_TX("Dumping TX packet frag %i of %i (%d bytes):\n",
6355                              i, tfd->u.data.num_chunks,
6356                              txb->fragments[i]->len - hdr_len);
6357                 printk_buf(IPW_DL_TX, txb->fragments[i]->data + hdr_len,
6358                            txb->fragments[i]->len - hdr_len);
6359
6360                 tfd->u.data.chunk_ptr[i] = pci_map_single(
6361                         priv->pci_dev, txb->fragments[i]->data + hdr_len,
6362                         txb->fragments[i]->len - hdr_len, PCI_DMA_TODEVICE);
6363                 tfd->u.data.chunk_len[i] = txb->fragments[i]->len - hdr_len;
6364         }
6365
6366         if (i != txb->nr_frags) {
6367                 struct sk_buff *skb;
6368                 u16 remaining_bytes = 0;
6369                 int j;
6370
6371                 for (j = i; j < txb->nr_frags; j++)
6372                         remaining_bytes += txb->fragments[j]->len - hdr_len;
6373
6374                 printk(KERN_INFO "Trying to reallocate for %d bytes\n",
6375                        remaining_bytes);
6376                 skb = alloc_skb(remaining_bytes, GFP_ATOMIC);
6377                 if (skb != NULL) {
6378                         tfd->u.data.chunk_len[i] = remaining_bytes;
6379                         for (j = i; j < txb->nr_frags; j++) {
6380                                 int size = txb->fragments[j]->len - hdr_len;
6381                                 printk(KERN_INFO "Adding frag %d %d...\n",
6382                                         j, size);
6383                                 memcpy(skb_put(skb, size),
6384                                         txb->fragments[j]->data + hdr_len,
6385                                         size);
6386                         }
6387                         dev_kfree_skb_any(txb->fragments[i]);
6388                         txb->fragments[i] = skb;
6389                         tfd->u.data.chunk_ptr[i] = pci_map_single(
6390                                 priv->pci_dev, skb->data,
6391                                 tfd->u.data.chunk_len[i], PCI_DMA_TODEVICE);
6392                         tfd->u.data.num_chunks++;
6393                 }
6394         }
6395
6396         /* kick DMA */
6397         q->first_empty = ipw_queue_inc_wrap(q->first_empty, q->n_bd);
6398         ipw_write32(priv, q->reg_w, q->first_empty);
6399
6400         if (ipw_queue_space(q) < q->high_mark)
6401                 netif_stop_queue(priv->net_dev);
6402
6403         return;
6404
6405  drop:
6406         IPW_DEBUG_DROP("Silently dropping Tx packet.\n");
6407         ieee80211_txb_free(txb);
6408 }
6409
6410 static int ipw_net_hard_start_xmit(struct ieee80211_txb *txb,
6411                                    struct net_device *dev)
6412 {
6413         struct ipw_priv *priv = ieee80211_priv(dev);
6414         unsigned long flags;
6415
6416         IPW_DEBUG_TX("dev->xmit(%d bytes)\n", txb->payload_size);
6417
6418         spin_lock_irqsave(&priv->lock, flags);
6419
6420         if (!(priv->status & STATUS_ASSOCIATED)) {
6421                 IPW_DEBUG_INFO("Tx attempt while not associated.\n");
6422                 priv->ieee->stats.tx_carrier_errors++;
6423                 netif_stop_queue(dev);
6424                 goto fail_unlock;
6425         }
6426
6427         ipw_tx_skb(priv, txb);
6428
6429         spin_unlock_irqrestore(&priv->lock, flags);
6430         return 0;
6431
6432  fail_unlock:
6433         spin_unlock_irqrestore(&priv->lock, flags);
6434         return 1;
6435 }
6436
6437 static struct net_device_stats *ipw_net_get_stats(struct net_device *dev)
6438 {
6439         struct ipw_priv *priv = ieee80211_priv(dev);
6440
6441         priv->ieee->stats.tx_packets = priv->tx_packets;
6442         priv->ieee->stats.rx_packets = priv->rx_packets;
6443         return &priv->ieee->stats;
6444 }
6445
6446 static void ipw_net_set_multicast_list(struct net_device *dev)
6447 {
6448
6449 }
6450
6451 static int ipw_net_set_mac_address(struct net_device *dev, void *p)
6452 {
6453         struct ipw_priv *priv = ieee80211_priv(dev);
6454         struct sockaddr *addr = p;
6455         if (!is_valid_ether_addr(addr->sa_data))
6456                 return -EADDRNOTAVAIL;
6457         priv->config |= CFG_CUSTOM_MAC;
6458         memcpy(priv->mac_addr, addr->sa_data, ETH_ALEN);
6459         printk(KERN_INFO "%s: Setting MAC to " MAC_FMT "\n",
6460                priv->net_dev->name, MAC_ARG(priv->mac_addr));
6461         ipw_adapter_restart(priv);
6462         return 0;
6463 }
6464
6465 static void ipw_ethtool_get_drvinfo(struct net_device *dev,
6466                                     struct ethtool_drvinfo *info)
6467 {
6468         struct ipw_priv *p = ieee80211_priv(dev);
6469         char vers[64];
6470         char date[32];
6471         u32 len;
6472
6473         strcpy(info->driver, DRV_NAME);
6474         strcpy(info->version, DRV_VERSION);
6475
6476         len = sizeof(vers);
6477         ipw_get_ordinal(p, IPW_ORD_STAT_FW_VERSION, vers, &len);
6478         len = sizeof(date);
6479         ipw_get_ordinal(p, IPW_ORD_STAT_FW_DATE, date, &len);
6480
6481         snprintf(info->fw_version, sizeof(info->fw_version),"%s (%s)",
6482                  vers, date);
6483         strcpy(info->bus_info, pci_name(p->pci_dev));
6484         info->eedump_len = CX2_EEPROM_IMAGE_SIZE;
6485 }
6486
6487 static u32 ipw_ethtool_get_link(struct net_device *dev)
6488 {
6489         struct ipw_priv *priv = ieee80211_priv(dev);
6490         return (priv->status & STATUS_ASSOCIATED) != 0;
6491 }
6492
6493 static int ipw_ethtool_get_eeprom_len(struct net_device *dev)
6494 {
6495         return CX2_EEPROM_IMAGE_SIZE;
6496 }
6497
6498 static int ipw_ethtool_get_eeprom(struct net_device *dev,
6499                                   struct ethtool_eeprom *eeprom, u8 *bytes)
6500 {
6501         struct ipw_priv *p = ieee80211_priv(dev);
6502
6503         if (eeprom->offset + eeprom->len > CX2_EEPROM_IMAGE_SIZE)
6504                 return -EINVAL;
6505
6506         memcpy(bytes, &((u8 *)p->eeprom)[eeprom->offset], eeprom->len);
6507         return 0;
6508 }
6509
6510 static int ipw_ethtool_set_eeprom(struct net_device *dev,
6511                                   struct ethtool_eeprom *eeprom, u8 *bytes)
6512 {
6513         struct ipw_priv *p = ieee80211_priv(dev);
6514         int i;
6515
6516         if (eeprom->offset + eeprom->len > CX2_EEPROM_IMAGE_SIZE)
6517                 return -EINVAL;
6518
6519         memcpy(&((u8 *)p->eeprom)[eeprom->offset], bytes, eeprom->len);
6520         for (i = IPW_EEPROM_DATA;
6521              i < IPW_EEPROM_DATA + CX2_EEPROM_IMAGE_SIZE;
6522              i++)
6523                 ipw_write8(p, i, p->eeprom[i]);
6524
6525         return 0;
6526 }
6527
6528 static struct ethtool_ops ipw_ethtool_ops = {
6529          .get_link       = ipw_ethtool_get_link,
6530          .get_drvinfo    = ipw_ethtool_get_drvinfo,
6531          .get_eeprom_len = ipw_ethtool_get_eeprom_len,
6532          .get_eeprom     = ipw_ethtool_get_eeprom,
6533          .set_eeprom     = ipw_ethtool_set_eeprom,
6534 };
6535
6536 static irqreturn_t ipw_isr(int irq, void *data, struct pt_regs *regs)
6537 {
6538         struct ipw_priv *priv = data;
6539         u32 inta, inta_mask;
6540
6541         if (!priv)
6542                 return IRQ_NONE;
6543
6544         spin_lock(&priv->lock);
6545
6546         if (!(priv->status & STATUS_INT_ENABLED)) {
6547                 /* Shared IRQ */
6548                 goto none;
6549         }
6550
6551         inta = ipw_read32(priv, CX2_INTA_RW);
6552         inta_mask = ipw_read32(priv, CX2_INTA_MASK_R);
6553
6554         if (inta == 0xFFFFFFFF) {
6555                 /* Hardware disappeared */
6556                 IPW_WARNING("IRQ INTA == 0xFFFFFFFF\n");
6557                 goto none;
6558         }
6559
6560         if (!(inta & (CX2_INTA_MASK_ALL & inta_mask))) {
6561                 /* Shared interrupt */
6562                 goto none;
6563         }
6564
6565         /* tell the device to stop sending interrupts */
6566         ipw_disable_interrupts(priv);
6567
6568         /* ack current interrupts */
6569         inta &= (CX2_INTA_MASK_ALL & inta_mask);
6570         ipw_write32(priv, CX2_INTA_RW, inta);
6571
6572         /* Cache INTA value for our tasklet */
6573         priv->isr_inta = inta;
6574
6575         tasklet_schedule(&priv->irq_tasklet);
6576
6577         spin_unlock(&priv->lock);
6578
6579         return IRQ_HANDLED;
6580  none:
6581         spin_unlock(&priv->lock);
6582         return IRQ_NONE;
6583 }
6584
6585 static void ipw_rf_kill(void *adapter)
6586 {
6587         struct ipw_priv *priv = adapter;
6588         unsigned long flags;
6589
6590         spin_lock_irqsave(&priv->lock, flags);
6591
6592         if (rf_kill_active(priv)) {
6593                 IPW_DEBUG_RF_KILL("RF Kill active, rescheduling GPIO check\n");
6594                 if (priv->workqueue)
6595                         queue_delayed_work(priv->workqueue,
6596                                            &priv->rf_kill, 2 * HZ);
6597                 goto exit_unlock;
6598         }
6599
6600         /* RF Kill is now disabled, so bring the device back up */
6601
6602         if (!(priv->status & STATUS_RF_KILL_MASK)) {
6603                 IPW_DEBUG_RF_KILL("HW RF Kill no longer active, restarting "
6604                                   "device\n");
6605
6606                 /* we can not do an adapter restart while inside an irq lock */
6607                 queue_work(priv->workqueue, &priv->adapter_restart);
6608         } else
6609                 IPW_DEBUG_RF_KILL("HW RF Kill deactivated.  SW RF Kill still "
6610                                   "enabled\n");
6611
6612  exit_unlock:
6613         spin_unlock_irqrestore(&priv->lock, flags);
6614 }
6615
6616 static int ipw_setup_deferred_work(struct ipw_priv *priv)
6617 {
6618         int ret = 0;
6619
6620 #ifdef CONFIG_SOFTWARE_SUSPEND2
6621         priv->workqueue = create_workqueue(DRV_NAME, 0);
6622 #else
6623         priv->workqueue = create_workqueue(DRV_NAME);
6624 #endif
6625         init_waitqueue_head(&priv->wait_command_queue);
6626
6627         INIT_WORK(&priv->adhoc_check, ipw_adhoc_check, priv);
6628         INIT_WORK(&priv->associate, ipw_associate, priv);
6629         INIT_WORK(&priv->disassociate, ipw_disassociate, priv);
6630         INIT_WORK(&priv->rx_replenish, ipw_rx_queue_replenish, priv);
6631         INIT_WORK(&priv->adapter_restart, ipw_adapter_restart, priv);
6632         INIT_WORK(&priv->rf_kill, ipw_rf_kill, priv);
6633         INIT_WORK(&priv->up, (void (*)(void *))ipw_up, priv);
6634         INIT_WORK(&priv->down, (void (*)(void *))ipw_down, priv);
6635         INIT_WORK(&priv->request_scan,
6636                   (void (*)(void *))ipw_request_scan, priv);
6637         INIT_WORK(&priv->gather_stats,
6638                   (void (*)(void *))ipw_gather_stats, priv);
6639         INIT_WORK(&priv->abort_scan, (void (*)(void *))ipw_abort_scan, priv);
6640         INIT_WORK(&priv->roam, ipw_roam, priv);
6641         INIT_WORK(&priv->scan_check, ipw_scan_check, priv);
6642
6643         tasklet_init(&priv->irq_tasklet, (void (*)(unsigned long))
6644                      ipw_irq_tasklet, (unsigned long)priv);
6645
6646         return ret;
6647 }
6648
6649
6650 static void shim__set_security(struct net_device *dev,
6651                                struct ieee80211_security *sec)
6652 {
6653         struct ipw_priv *priv = ieee80211_priv(dev);
6654         int i;
6655
6656         for (i = 0; i < 4; i++) {
6657                 if (sec->flags & (1 << i)) {
6658                         priv->sec.key_sizes[i] = sec->key_sizes[i];
6659                         if (sec->key_sizes[i] == 0)
6660                                 priv->sec.flags &= ~(1 << i);
6661                         else
6662                                 memcpy(priv->sec.keys[i], sec->keys[i],
6663                                        sec->key_sizes[i]);
6664                         priv->sec.flags |= (1 << i);
6665                         priv->status |= STATUS_SECURITY_UPDATED;
6666                 }
6667         }
6668
6669         if ((sec->flags & SEC_ACTIVE_KEY) &&
6670             priv->sec.active_key != sec->active_key) {
6671                 if (sec->active_key <= 3) {
6672                         priv->sec.active_key = sec->active_key;
6673                         priv->sec.flags |= SEC_ACTIVE_KEY;
6674                 } else
6675                         priv->sec.flags &= ~SEC_ACTIVE_KEY;
6676                 priv->status |= STATUS_SECURITY_UPDATED;
6677         }
6678
6679         if ((sec->flags & SEC_AUTH_MODE) &&
6680             (priv->sec.auth_mode != sec->auth_mode)) {
6681                 priv->sec.auth_mode = sec->auth_mode;
6682                 priv->sec.flags |= SEC_AUTH_MODE;
6683                 if (sec->auth_mode == WLAN_AUTH_SHARED_KEY)
6684                         priv->capability |= CAP_SHARED_KEY;
6685                 else
6686                         priv->capability &= ~CAP_SHARED_KEY;
6687                 priv->status |= STATUS_SECURITY_UPDATED;
6688         }
6689
6690         if (sec->flags & SEC_ENABLED &&
6691             priv->sec.enabled != sec->enabled) {
6692                 priv->sec.flags |= SEC_ENABLED;
6693                 priv->sec.enabled = sec->enabled;
6694                 priv->status |= STATUS_SECURITY_UPDATED;
6695                 if (sec->enabled)
6696                         priv->capability |= CAP_PRIVACY_ON;
6697                 else
6698                         priv->capability &= ~CAP_PRIVACY_ON;
6699         }
6700
6701         if (sec->flags & SEC_LEVEL &&
6702             priv->sec.level != sec->level) {
6703                 priv->sec.level = sec->level;
6704                 priv->sec.flags |= SEC_LEVEL;
6705                 priv->status |= STATUS_SECURITY_UPDATED;
6706         }
6707
6708         /* To match current functionality of ipw2100 (which works well w/
6709          * various supplicants, we don't force a disassociate if the
6710          * privacy capability changes ... */
6711 #if 0
6712         if ((priv->status & (STATUS_ASSOCIATED | STATUS_ASSOCIATING)) &&
6713             (((priv->assoc_request.capability &
6714                WLAN_CAPABILITY_PRIVACY) && !sec->enabled) ||
6715              (!(priv->assoc_request.capability &
6716                  WLAN_CAPABILITY_PRIVACY) && sec->enabled))) {
6717                 IPW_DEBUG_ASSOC("Disassociating due to capability "
6718                                 "change.\n");
6719                 ipw_disassociate(priv);
6720         }
6721 #endif
6722 }
6723
6724 static int init_supported_rates(struct ipw_priv *priv,
6725                                 struct ipw_supported_rates *rates)
6726 {
6727         /* TODO: Mask out rates based on priv->rates_mask */
6728
6729         memset(rates, 0, sizeof(*rates));
6730         /* configure supported rates */
6731         switch (priv->ieee->freq_band) {
6732         case IEEE80211_52GHZ_BAND:
6733                 rates->ieee_mode = IPW_A_MODE;
6734                 rates->purpose = IPW_RATE_CAPABILITIES;
6735                 ipw_add_ofdm_scan_rates(rates, IEEE80211_CCK_MODULATION,
6736                                         IEEE80211_OFDM_DEFAULT_RATES_MASK);
6737                 break;
6738
6739         default: /* Mixed or 2.4Ghz */
6740                 rates->ieee_mode = IPW_G_MODE;
6741                 rates->purpose = IPW_RATE_CAPABILITIES;
6742                 ipw_add_cck_scan_rates(rates, IEEE80211_CCK_MODULATION,
6743                                        IEEE80211_CCK_DEFAULT_RATES_MASK);
6744                 if (priv->ieee->modulation & IEEE80211_OFDM_MODULATION) {
6745                         ipw_add_ofdm_scan_rates(rates, IEEE80211_CCK_MODULATION,
6746                                                 IEEE80211_OFDM_DEFAULT_RATES_MASK);
6747                 }
6748                 break;
6749         }
6750
6751         return 0;
6752 }
6753
6754 static int ipw_config(struct ipw_priv *priv)
6755 {
6756         int i;
6757         struct ipw_tx_power tx_power;
6758
6759         memset(&priv->sys_config, 0, sizeof(priv->sys_config));
6760         memset(&tx_power, 0, sizeof(tx_power));
6761
6762         /* This is only called from ipw_up, which resets/reloads the firmware
6763            so, we don't need to first disable the card before we configure
6764            it */
6765
6766         /* configure device for 'G' band */
6767         tx_power.ieee_mode = IPW_G_MODE;
6768         tx_power.num_channels = 11;
6769         for (i = 0; i < 11; i++) {
6770                 tx_power.channels_tx_power[i].channel_number = i + 1;
6771                 tx_power.channels_tx_power[i].tx_power = priv->tx_power;
6772         }
6773         if (ipw_send_tx_power(priv, &tx_power))
6774                 goto error;
6775
6776         /* configure device to also handle 'B' band */
6777         tx_power.ieee_mode = IPW_B_MODE;
6778         if (ipw_send_tx_power(priv, &tx_power))
6779                 goto error;
6780
6781         /* initialize adapter address */
6782         if (ipw_send_adapter_address(priv, priv->net_dev->dev_addr))
6783                 goto error;
6784
6785         /* set basic system config settings */
6786         init_sys_config(&priv->sys_config);
6787         if (ipw_send_system_config(priv, &priv->sys_config))
6788                 goto error;
6789
6790         init_supported_rates(priv, &priv->rates);
6791         if (ipw_send_supported_rates(priv, &priv->rates))
6792                 goto error;
6793
6794         /* Set request-to-send threshold */
6795         if (priv->rts_threshold) {
6796                 if (ipw_send_rts_threshold(priv, priv->rts_threshold))
6797                         goto error;
6798         }
6799
6800         if (ipw_set_random_seed(priv))
6801                 goto error;
6802
6803         /* final state transition to the RUN state */
6804         if (ipw_send_host_complete(priv))
6805                 goto error;
6806
6807         /* If configured to try and auto-associate, kick off a scan */
6808         if ((priv->config & CFG_ASSOCIATE) && ipw_request_scan(priv))
6809                 goto error;
6810
6811         return 0;
6812
6813  error:
6814         return -EIO;
6815 }
6816
6817 #define MAX_HW_RESTARTS 5
6818 static int ipw_up(struct ipw_priv *priv)
6819 {
6820         int rc, i;
6821
6822         if (priv->status & STATUS_EXIT_PENDING)
6823                 return -EIO;
6824
6825         for (i = 0; i < MAX_HW_RESTARTS; i++ ) {
6826                 /* Load the microcode, firmware, and eeprom.
6827                  * Also start the clocks. */
6828                 rc = ipw_load(priv);
6829                 if (rc) {
6830                         IPW_ERROR("Unable to load firmware: 0x%08X\n",
6831                                         rc);
6832                         return rc;
6833                 }
6834
6835                 ipw_init_ordinals(priv);
6836                 if (!(priv->config & CFG_CUSTOM_MAC))
6837                         eeprom_parse_mac(priv, priv->mac_addr);
6838                 memcpy(priv->net_dev->dev_addr, priv->mac_addr, ETH_ALEN);
6839
6840                 if (priv->status & STATUS_RF_KILL_MASK)
6841                         return 0;
6842
6843                 rc = ipw_config(priv);
6844                 if (!rc) {
6845                         IPW_DEBUG_INFO("Configured device on count %i\n", i);
6846                         priv->notif_missed_beacons = 0;
6847                         netif_start_queue(priv->net_dev);
6848                         return 0;
6849                 } else {
6850                         IPW_DEBUG_INFO("Device configuration failed: 0x%08X\n",
6851                                        rc);
6852                 }
6853
6854                 IPW_DEBUG_INFO("Failed to config device on retry %d of %d\n",
6855                                i, MAX_HW_RESTARTS);
6856
6857                 /* We had an error bringing up the hardware, so take it
6858                  * all the way back down so we can try again */
6859                 ipw_down(priv);
6860         }
6861
6862         /* tried to restart and config the device for as long as our
6863          * patience could withstand */
6864         IPW_ERROR("Unable to initialize device after %d attempts.\n",
6865                   i);
6866         return -EIO;
6867 }
6868
6869 static void ipw_down(struct ipw_priv *priv)
6870 {
6871         /* Attempt to disable the card */
6872 #if 0
6873         ipw_send_card_disable(priv, 0);
6874 #endif
6875
6876         /* tell the device to stop sending interrupts */
6877         ipw_disable_interrupts(priv);
6878
6879         /* Clear all bits but the RF Kill */
6880         priv->status &= STATUS_RF_KILL_MASK;
6881
6882         netif_carrier_off(priv->net_dev);
6883         netif_stop_queue(priv->net_dev);
6884
6885         ipw_stop_nic(priv);
6886 }
6887
6888 /* Called by register_netdev() */
6889 static int ipw_net_init(struct net_device *dev)
6890 {
6891         struct ipw_priv *priv = ieee80211_priv(dev);
6892
6893         if (priv->status & STATUS_RF_KILL_SW) {
6894                 IPW_WARNING("Radio disabled by module parameter.\n");
6895                 return 0;
6896         } else if (rf_kill_active(priv)) {
6897                 IPW_WARNING("Radio Frequency Kill Switch is On:\n"
6898                             "Kill switch must be turned off for "
6899                             "wireless networking to work.\n");
6900                 queue_delayed_work(priv->workqueue, &priv->rf_kill, 2 * HZ);
6901                 return 0;
6902         }
6903
6904         if (ipw_up(priv))
6905                 return -EIO;
6906
6907         return 0;
6908 }
6909
6910 /* PCI driver stuff */
6911 static struct pci_device_id card_ids[] = {
6912         {PCI_VENDOR_ID_INTEL, 0x1043, 0x8086, 0x2701, 0, 0, 0},
6913         {PCI_VENDOR_ID_INTEL, 0x1043, 0x8086, 0x2702, 0, 0, 0},
6914         {PCI_VENDOR_ID_INTEL, 0x1043, 0x8086, 0x2711, 0, 0, 0},
6915         {PCI_VENDOR_ID_INTEL, 0x1043, 0x8086, 0x2712, 0, 0, 0},
6916         {PCI_VENDOR_ID_INTEL, 0x1043, 0x8086, 0x2721, 0, 0, 0},
6917         {PCI_VENDOR_ID_INTEL, 0x1043, 0x8086, 0x2722, 0, 0, 0},
6918         {PCI_VENDOR_ID_INTEL, 0x1043, 0x8086, 0x2731, 0, 0, 0},
6919         {PCI_VENDOR_ID_INTEL, 0x1043, 0x8086, 0x2732, 0, 0, 0},
6920         {PCI_VENDOR_ID_INTEL, 0x1043, 0x8086, 0x2741, 0, 0, 0},
6921         {PCI_VENDOR_ID_INTEL, 0x1043, 0x103c, 0x2741, 0, 0, 0},
6922         {PCI_VENDOR_ID_INTEL, 0x1043, 0x8086, 0x2742, 0, 0, 0},
6923         {PCI_VENDOR_ID_INTEL, 0x1043, 0x8086, 0x2751, 0, 0, 0},
6924         {PCI_VENDOR_ID_INTEL, 0x1043, 0x8086, 0x2752, 0, 0, 0},
6925         {PCI_VENDOR_ID_INTEL, 0x1043, 0x8086, 0x2753, 0, 0, 0},
6926         {PCI_VENDOR_ID_INTEL, 0x1043, 0x8086, 0x2754, 0, 0, 0},
6927         {PCI_VENDOR_ID_INTEL, 0x1043, 0x8086, 0x2761, 0, 0, 0},
6928         {PCI_VENDOR_ID_INTEL, 0x1043, 0x8086, 0x2762, 0, 0, 0},
6929         {PCI_VENDOR_ID_INTEL, 0x104f, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
6930         {PCI_VENDOR_ID_INTEL, 0x4220, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0}, /* BG */
6931         {PCI_VENDOR_ID_INTEL, 0x4221, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0}, /* 2225BG */
6932         {PCI_VENDOR_ID_INTEL, 0x4223, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0}, /* ABG */
6933         {PCI_VENDOR_ID_INTEL, 0x4224, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0}, /* ABG */
6934
6935         /* required last entry */
6936         {0,}
6937 };
6938
6939 MODULE_DEVICE_TABLE(pci, card_ids);
6940
6941 static struct attribute *ipw_sysfs_entries[] = {
6942         &dev_attr_rf_kill.attr,
6943         &dev_attr_direct_dword.attr,
6944         &dev_attr_indirect_byte.attr,
6945         &dev_attr_indirect_dword.attr,
6946         &dev_attr_mem_gpio_reg.attr,
6947         &dev_attr_command_event_reg.attr,
6948         &dev_attr_nic_type.attr,
6949         &dev_attr_status.attr,
6950         &dev_attr_cfg.attr,
6951         &dev_attr_dump_errors.attr,
6952         &dev_attr_dump_events.attr,
6953         &dev_attr_eeprom_delay.attr,
6954         &dev_attr_ucode_version.attr,
6955         &dev_attr_rtc.attr,
6956         NULL
6957 };
6958
6959 static struct attribute_group ipw_attribute_group = {
6960         .name = NULL,           /* put in device directory */
6961         .attrs  = ipw_sysfs_entries,
6962 };
6963
6964 static int ipw_pci_probe(struct pci_dev *pdev,
6965                          const struct pci_device_id *ent)
6966 {
6967         int err = 0;
6968         struct net_device *net_dev;
6969         void __iomem *base;
6970         u32 length, val;
6971         struct ipw_priv *priv;
6972         int band, modulation;
6973
6974         net_dev = alloc_ieee80211(sizeof(struct ipw_priv));
6975         if (net_dev == NULL) {
6976                 err = -ENOMEM;
6977                 goto out;
6978         }
6979
6980         priv = ieee80211_priv(net_dev);
6981         priv->ieee = netdev_priv(net_dev);
6982         priv->net_dev = net_dev;
6983         priv->pci_dev = pdev;
6984 #ifdef CONFIG_IPW_DEBUG
6985         ipw_debug_level = debug;
6986 #endif
6987         spin_lock_init(&priv->lock);
6988
6989         if (pci_enable_device(pdev)) {
6990                 err = -ENODEV;
6991                 goto out_free_ieee80211;
6992         }
6993
6994         pci_set_master(pdev);
6995
6996         err = pci_set_dma_mask(pdev, DMA_32BIT_MASK);
6997         if (!err)
6998                 err = pci_set_consistent_dma_mask(pdev, DMA_32BIT_MASK);
6999         if (err) {
7000                 printk(KERN_WARNING DRV_NAME ": No suitable DMA available.\n");
7001                 goto out_pci_disable_device;
7002         }
7003
7004         pci_set_drvdata(pdev, priv);
7005
7006         err = pci_request_regions(pdev, DRV_NAME);
7007         if (err)
7008                 goto out_pci_disable_device;
7009
7010         /* We disable the RETRY_TIMEOUT register (0x41) to keep
7011          * PCI Tx retries from interfering with C3 CPU state */
7012         pci_read_config_dword(pdev, 0x40, &val);
7013         if ((val & 0x0000ff00) != 0)
7014                 pci_write_config_dword(pdev, 0x40, val & 0xffff00ff);
7015
7016         length = pci_resource_len(pdev, 0);
7017         priv->hw_len = length;
7018
7019         base = ioremap_nocache(pci_resource_start(pdev, 0), length);
7020         if (!base) {
7021                 err = -ENODEV;
7022                 goto out_pci_release_regions;
7023         }
7024
7025         priv->hw_base = base;
7026         IPW_DEBUG_INFO("pci_resource_len = 0x%08x\n", length);
7027         IPW_DEBUG_INFO("pci_resource_base = %p\n", base);
7028
7029         err = ipw_setup_deferred_work(priv);
7030         if (err) {
7031                 IPW_ERROR("Unable to setup deferred work\n");
7032                 goto out_iounmap;
7033         }
7034
7035         /* Initialize module parameter values here */
7036         if (ifname)
7037                 strncpy(net_dev->name, ifname, IFNAMSIZ);
7038
7039         if (associate)
7040                 priv->config |= CFG_ASSOCIATE;
7041         else
7042                 IPW_DEBUG_INFO("Auto associate disabled.\n");
7043
7044         if (auto_create)
7045                 priv->config |= CFG_ADHOC_CREATE;
7046         else
7047                 IPW_DEBUG_INFO("Auto adhoc creation disabled.\n");
7048
7049         if (disable) {
7050                 priv->status |= STATUS_RF_KILL_SW;
7051                 IPW_DEBUG_INFO("Radio disabled.\n");
7052         }
7053
7054         if (channel != 0) {
7055                 priv->config |= CFG_STATIC_CHANNEL;
7056                 priv->channel = channel;
7057                 IPW_DEBUG_INFO("Bind to static channel %d\n", channel);
7058                 IPW_DEBUG_INFO("Bind to static channel %d\n", channel);
7059                 /* TODO: Validate that provided channel is in range */
7060         }
7061
7062         switch (mode) {
7063         case 1:
7064                 priv->ieee->iw_mode = IW_MODE_ADHOC;
7065                 break;
7066 #ifdef CONFIG_IPW_PROMISC
7067         case 2:
7068                 priv->ieee->iw_mode = IW_MODE_MONITOR;
7069                 break;
7070 #endif
7071         default:
7072         case 0:
7073                 priv->ieee->iw_mode = IW_MODE_INFRA;
7074                 break;
7075         }
7076
7077         if ((priv->pci_dev->device == 0x4223) ||
7078             (priv->pci_dev->device == 0x4224)) {
7079                 printk(KERN_INFO DRV_NAME
7080                        ": Detected Intel PRO/Wireless 2915ABG Network "
7081                        "Connection\n");
7082                 priv->ieee->abg_ture = 1;
7083                 band = IEEE80211_52GHZ_BAND | IEEE80211_24GHZ_BAND;
7084                 modulation = IEEE80211_OFDM_MODULATION |
7085                         IEEE80211_CCK_MODULATION;
7086                 priv->adapter = IPW_2915ABG;
7087                 priv->ieee->mode = IEEE_A|IEEE_G|IEEE_B;
7088         } else {
7089                 if (priv->pci_dev->device == 0x4221)
7090                         printk(KERN_INFO DRV_NAME
7091                                ": Detected Intel PRO/Wireless 2225BG Network "
7092                                "Connection\n");
7093                 else
7094                         printk(KERN_INFO DRV_NAME
7095                                ": Detected Intel PRO/Wireless 2200BG Network "
7096                                "Connection\n");
7097
7098                 priv->ieee->abg_ture = 0;
7099                 band = IEEE80211_24GHZ_BAND;
7100                 modulation = IEEE80211_OFDM_MODULATION |
7101                         IEEE80211_CCK_MODULATION;
7102                 priv->adapter = IPW_2200BG;
7103                 priv->ieee->mode = IEEE_G|IEEE_B;
7104         }
7105
7106         priv->ieee->freq_band = band;
7107         priv->ieee->modulation = modulation;
7108
7109         priv->rates_mask = IEEE80211_DEFAULT_RATES_MASK;
7110
7111         priv->missed_beacon_threshold = IPW_MB_DISASSOCIATE_THRESHOLD_DEFAULT;
7112         priv->roaming_threshold = IPW_MB_ROAMING_THRESHOLD_DEFAULT;
7113
7114         priv->rts_threshold = DEFAULT_RTS_THRESHOLD;
7115
7116         /* If power management is turned on, default to AC mode */
7117         priv->power_mode = IPW_POWER_AC;
7118         priv->tx_power = IPW_DEFAULT_TX_POWER;
7119
7120         err = request_irq(pdev->irq, ipw_isr, SA_SHIRQ, DRV_NAME,
7121                           priv);
7122         if (err) {
7123                 IPW_ERROR("Error allocating IRQ %d\n", pdev->irq);
7124                 goto out_destroy_workqueue;
7125         }
7126
7127         SET_MODULE_OWNER(net_dev);
7128         SET_NETDEV_DEV(net_dev, &pdev->dev);
7129
7130         priv->ieee->hard_start_xmit = ipw_net_hard_start_xmit;
7131         priv->ieee->set_security = shim__set_security;
7132
7133         net_dev->open = ipw_net_open;
7134         net_dev->stop = ipw_net_stop;
7135         net_dev->init = ipw_net_init;
7136         net_dev->get_stats = ipw_net_get_stats;
7137         net_dev->set_multicast_list = ipw_net_set_multicast_list;
7138         net_dev->set_mac_address = ipw_net_set_mac_address;
7139         net_dev->get_wireless_stats = ipw_get_wireless_stats;
7140         net_dev->wireless_handlers = &ipw_wx_handler_def;
7141         net_dev->ethtool_ops = &ipw_ethtool_ops;
7142         net_dev->irq = pdev->irq;
7143         net_dev->base_addr = (unsigned long )priv->hw_base;
7144         net_dev->mem_start = pci_resource_start(pdev, 0);
7145         net_dev->mem_end = net_dev->mem_start + pci_resource_len(pdev, 0) - 1;
7146
7147         err = sysfs_create_group(&pdev->dev.kobj, &ipw_attribute_group);
7148         if (err) {
7149                 IPW_ERROR("failed to create sysfs device attributes\n");
7150                 goto out_release_irq;
7151         }
7152
7153         err = register_netdev(net_dev);
7154         if (err) {
7155                 IPW_ERROR("failed to register network device\n");
7156                 goto out_remove_group;
7157         }
7158
7159         return 0;
7160
7161  out_remove_group:
7162         sysfs_remove_group(&pdev->dev.kobj, &ipw_attribute_group);
7163  out_release_irq:
7164         free_irq(pdev->irq, priv);
7165  out_destroy_workqueue:
7166         destroy_workqueue(priv->workqueue);
7167         priv->workqueue = NULL;
7168  out_iounmap:
7169         iounmap(priv->hw_base);
7170  out_pci_release_regions:
7171         pci_release_regions(pdev);
7172  out_pci_disable_device:
7173         pci_disable_device(pdev);
7174         pci_set_drvdata(pdev, NULL);
7175  out_free_ieee80211:
7176         free_ieee80211(priv->net_dev);
7177  out:
7178         return err;
7179 }
7180
7181 static void ipw_pci_remove(struct pci_dev *pdev)
7182 {
7183         struct ipw_priv *priv = pci_get_drvdata(pdev);
7184         if (!priv)
7185                 return;
7186
7187         priv->status |= STATUS_EXIT_PENDING;
7188
7189         sysfs_remove_group(&pdev->dev.kobj, &ipw_attribute_group);
7190
7191         ipw_down(priv);
7192
7193         unregister_netdev(priv->net_dev);
7194
7195         if (priv->rxq) {
7196                 ipw_rx_queue_free(priv, priv->rxq);
7197                 priv->rxq = NULL;
7198         }
7199         ipw_tx_queue_free(priv);
7200
7201         /* ipw_down will ensure that there is no more pending work
7202          * in the workqueue's, so we can safely remove them now. */
7203         if (priv->workqueue) {
7204                 cancel_delayed_work(&priv->adhoc_check);
7205                 cancel_delayed_work(&priv->gather_stats);
7206                 cancel_delayed_work(&priv->request_scan);
7207                 cancel_delayed_work(&priv->rf_kill);
7208                 cancel_delayed_work(&priv->scan_check);
7209                 destroy_workqueue(priv->workqueue);
7210                 priv->workqueue = NULL;
7211         }
7212
7213         free_irq(pdev->irq, priv);
7214         iounmap(priv->hw_base);
7215         pci_release_regions(pdev);
7216         pci_disable_device(pdev);
7217         pci_set_drvdata(pdev, NULL);
7218         free_ieee80211(priv->net_dev);
7219
7220 #ifdef CONFIG_PM
7221         if (fw_loaded) {
7222                 release_firmware(bootfw);
7223                 release_firmware(ucode);
7224                 release_firmware(firmware);
7225                 fw_loaded = 0;
7226         }
7227 #endif
7228 }
7229
7230
7231 #ifdef CONFIG_PM
7232 static int ipw_pci_suspend(struct pci_dev *pdev, u32 state)
7233 {
7234         struct ipw_priv *priv = pci_get_drvdata(pdev);
7235         struct net_device *dev = priv->net_dev;
7236
7237         printk(KERN_INFO "%s: Going into suspend...\n", dev->name);
7238
7239         /* Take down the device; powers it off, etc. */
7240         ipw_down(priv);
7241
7242         /* Remove the PRESENT state of the device */
7243         netif_device_detach(dev);
7244
7245 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,10)
7246         pci_save_state(pdev, priv->pm_state);
7247 #else
7248         pci_save_state(pdev);
7249 #endif
7250         pci_disable_device(pdev);
7251         pci_set_power_state(pdev, state);
7252
7253         return 0;
7254 }
7255
7256 static int ipw_pci_resume(struct pci_dev *pdev)
7257 {
7258         struct ipw_priv *priv = pci_get_drvdata(pdev);
7259         struct net_device *dev = priv->net_dev;
7260         u32 val;
7261
7262         printk(KERN_INFO "%s: Coming out of suspend...\n", dev->name);
7263
7264         pci_set_power_state(pdev, 0);
7265         pci_enable_device(pdev);
7266 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,10)
7267         pci_restore_state(pdev, priv->pm_state);
7268 #else
7269         pci_restore_state(pdev);
7270 #endif
7271         /*
7272          * Suspend/Resume resets the PCI configuration space, so we have to
7273          * re-disable the RETRY_TIMEOUT register (0x41) to keep PCI Tx retries
7274          * from interfering with C3 CPU state. pci_restore_state won't help
7275          * here since it only restores the first 64 bytes pci config header.
7276          */
7277         pci_read_config_dword(pdev, 0x40, &val);
7278         if ((val & 0x0000ff00) != 0)
7279                 pci_write_config_dword(pdev, 0x40, val & 0xffff00ff);
7280
7281         /* Set the device back into the PRESENT state; this will also wake
7282          * the queue of needed */
7283         netif_device_attach(dev);
7284
7285         /* Bring the device back up */
7286         queue_work(priv->workqueue, &priv->up);
7287
7288         return 0;
7289 }
7290 #endif
7291
7292 /* driver initialization stuff */
7293 static struct pci_driver ipw_driver = {
7294         .name = DRV_NAME,
7295         .id_table = card_ids,
7296         .probe = ipw_pci_probe,
7297         .remove = __devexit_p(ipw_pci_remove),
7298 #ifdef CONFIG_PM
7299         .suspend = ipw_pci_suspend,
7300         .resume = ipw_pci_resume,
7301 #endif
7302 };
7303
7304 static int __init ipw_init(void)
7305 {
7306         int ret;
7307
7308         printk(KERN_INFO DRV_NAME ": " DRV_DESCRIPTION ", " DRV_VERSION "\n");
7309         printk(KERN_INFO DRV_NAME ": " DRV_COPYRIGHT "\n");
7310
7311         ret = pci_module_init(&ipw_driver);
7312         if (ret) {
7313                 IPW_ERROR("Unable to initialize PCI module\n");
7314                 return ret;
7315         }
7316
7317         ret = driver_create_file(&ipw_driver.driver,
7318                                  &driver_attr_debug_level);
7319         if (ret) {
7320                 IPW_ERROR("Unable to create driver sysfs file\n");
7321                 pci_unregister_driver(&ipw_driver);
7322                 return ret;
7323         }
7324
7325         return ret;
7326 }
7327
7328 static void __exit ipw_exit(void)
7329 {
7330         driver_remove_file(&ipw_driver.driver, &driver_attr_debug_level);
7331         pci_unregister_driver(&ipw_driver);
7332 }
7333
7334 module_param(disable, int, 0444);
7335 MODULE_PARM_DESC(disable, "manually disable the radio (default 0 [radio on])");
7336
7337 module_param(associate, int, 0444);
7338 MODULE_PARM_DESC(associate, "auto associate when scanning (default on)");
7339
7340 module_param(auto_create, int, 0444);
7341 MODULE_PARM_DESC(auto_create, "auto create adhoc network (default on)");
7342
7343 module_param(debug, int, 0444);
7344 MODULE_PARM_DESC(debug, "debug output mask");
7345
7346 module_param(channel, int, 0444);
7347 MODULE_PARM_DESC(channel, "channel to limit associate to (default 0 [ANY])");
7348
7349 module_param(ifname, charp, 0444);
7350 MODULE_PARM_DESC(ifname, "network device name (default eth%d)");
7351
7352 #ifdef CONFIG_IPW_PROMISC
7353 module_param(mode, int, 0444);
7354 MODULE_PARM_DESC(mode, "network mode (0=BSS,1=IBSS,2=Monitor)");
7355 #else
7356 module_param(mode, int, 0444);
7357 MODULE_PARM_DESC(mode, "network mode (0=BSS,1=IBSS)");
7358 #endif
7359
7360 module_exit(ipw_exit);
7361 module_init(ipw_init);