[PATCH] iwlwifi: Fix typo in rate sacling algorithm
[linux-2.6] / drivers / net / wireless / b43 / main.c
1 /*
2
3   Broadcom B43 wireless driver
4
5   Copyright (c) 2005 Martin Langer <martin-langer@gmx.de>
6   Copyright (c) 2005 Stefano Brivio <st3@riseup.net>
7   Copyright (c) 2005, 2006 Michael Buesch <mb@bu3sch.de>
8   Copyright (c) 2005 Danny van Dyk <kugelfang@gentoo.org>
9   Copyright (c) 2005 Andreas Jaggi <andreas.jaggi@waterwave.ch>
10
11   Some parts of the code in this file are derived from the ipw2200
12   driver  Copyright(c) 2003 - 2004 Intel Corporation.
13
14   This program is free software; you can redistribute it and/or modify
15   it under the terms of the GNU General Public License as published by
16   the Free Software Foundation; either version 2 of the License, or
17   (at your option) any later version.
18
19   This program is distributed in the hope that it will be useful,
20   but WITHOUT ANY WARRANTY; without even the implied warranty of
21   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22   GNU General Public License for more details.
23
24   You should have received a copy of the GNU General Public License
25   along with this program; see the file COPYING.  If not, write to
26   the Free Software Foundation, Inc., 51 Franklin Steet, Fifth Floor,
27   Boston, MA 02110-1301, USA.
28
29 */
30
31 #include <linux/delay.h>
32 #include <linux/init.h>
33 #include <linux/moduleparam.h>
34 #include <linux/if_arp.h>
35 #include <linux/etherdevice.h>
36 #include <linux/version.h>
37 #include <linux/firmware.h>
38 #include <linux/wireless.h>
39 #include <linux/workqueue.h>
40 #include <linux/skbuff.h>
41 #include <linux/dma-mapping.h>
42 #include <asm/unaligned.h>
43
44 #include "b43.h"
45 #include "main.h"
46 #include "debugfs.h"
47 #include "phy.h"
48 #include "dma.h"
49 #include "pio.h"
50 #include "sysfs.h"
51 #include "xmit.h"
52 #include "sysfs.h"
53 #include "lo.h"
54 #include "pcmcia.h"
55
56 MODULE_DESCRIPTION("Broadcom B43 wireless driver");
57 MODULE_AUTHOR("Martin Langer");
58 MODULE_AUTHOR("Stefano Brivio");
59 MODULE_AUTHOR("Michael Buesch");
60 MODULE_LICENSE("GPL");
61
62 extern char *nvram_get(char *name);
63
64 #if defined(CONFIG_B43_DMA) && defined(CONFIG_B43_PIO)
65 static int modparam_pio;
66 module_param_named(pio, modparam_pio, int, 0444);
67 MODULE_PARM_DESC(pio, "enable(1) / disable(0) PIO mode");
68 #elif defined(CONFIG_B43_DMA)
69 # define modparam_pio   0
70 #elif defined(CONFIG_B43_PIO)
71 # define modparam_pio   1
72 #endif
73
74 static int modparam_bad_frames_preempt;
75 module_param_named(bad_frames_preempt, modparam_bad_frames_preempt, int, 0444);
76 MODULE_PARM_DESC(bad_frames_preempt,
77                  "enable(1) / disable(0) Bad Frames Preemption");
78
79 static int modparam_short_retry = B43_DEFAULT_SHORT_RETRY_LIMIT;
80 module_param_named(short_retry, modparam_short_retry, int, 0444);
81 MODULE_PARM_DESC(short_retry, "Short-Retry-Limit (0 - 15)");
82
83 static int modparam_long_retry = B43_DEFAULT_LONG_RETRY_LIMIT;
84 module_param_named(long_retry, modparam_long_retry, int, 0444);
85 MODULE_PARM_DESC(long_retry, "Long-Retry-Limit (0 - 15)");
86
87 static int modparam_noleds;
88 module_param_named(noleds, modparam_noleds, int, 0444);
89 MODULE_PARM_DESC(noleds, "Turn off all LED activity");
90
91 static char modparam_fwpostfix[16];
92 module_param_string(fwpostfix, modparam_fwpostfix, 16, 0444);
93 MODULE_PARM_DESC(fwpostfix, "Postfix for the .fw files to load.");
94
95 static int modparam_hwpctl;
96 module_param_named(hwpctl, modparam_hwpctl, int, 0444);
97 MODULE_PARM_DESC(hwpctl, "Enable hardware-side power control (default off)");
98
99 static int modparam_nohwcrypt;
100 module_param_named(nohwcrypt, modparam_nohwcrypt, int, 0444);
101 MODULE_PARM_DESC(nohwcrypt, "Disable hardware encryption.");
102
103 static const struct ssb_device_id b43_ssb_tbl[] = {
104         SSB_DEVICE(SSB_VENDOR_BROADCOM, SSB_DEV_80211, 5),
105         SSB_DEVICE(SSB_VENDOR_BROADCOM, SSB_DEV_80211, 6),
106         SSB_DEVICE(SSB_VENDOR_BROADCOM, SSB_DEV_80211, 7),
107         SSB_DEVICE(SSB_VENDOR_BROADCOM, SSB_DEV_80211, 9),
108         SSB_DEVICE(SSB_VENDOR_BROADCOM, SSB_DEV_80211, 10),
109         SSB_DEVTABLE_END
110 };
111
112 MODULE_DEVICE_TABLE(ssb, b43_ssb_tbl);
113
114 /* Channel and ratetables are shared for all devices.
115  * They can't be const, because ieee80211 puts some precalculated
116  * data in there. This data is the same for all devices, so we don't
117  * get concurrency issues */
118 #define RATETAB_ENT(_rateid, _flags) \
119         {                                                       \
120                 .rate   = B43_RATE_TO_BASE100KBPS(_rateid),     \
121                 .val    = (_rateid),                            \
122                 .val2   = (_rateid),                            \
123                 .flags  = (_flags),                             \
124         }
125 static struct ieee80211_rate __b43_ratetable[] = {
126         RATETAB_ENT(B43_CCK_RATE_1MB, IEEE80211_RATE_CCK),
127         RATETAB_ENT(B43_CCK_RATE_2MB, IEEE80211_RATE_CCK_2),
128         RATETAB_ENT(B43_CCK_RATE_5MB, IEEE80211_RATE_CCK_2),
129         RATETAB_ENT(B43_CCK_RATE_11MB, IEEE80211_RATE_CCK_2),
130         RATETAB_ENT(B43_OFDM_RATE_6MB, IEEE80211_RATE_OFDM),
131         RATETAB_ENT(B43_OFDM_RATE_9MB, IEEE80211_RATE_OFDM),
132         RATETAB_ENT(B43_OFDM_RATE_12MB, IEEE80211_RATE_OFDM),
133         RATETAB_ENT(B43_OFDM_RATE_18MB, IEEE80211_RATE_OFDM),
134         RATETAB_ENT(B43_OFDM_RATE_24MB, IEEE80211_RATE_OFDM),
135         RATETAB_ENT(B43_OFDM_RATE_36MB, IEEE80211_RATE_OFDM),
136         RATETAB_ENT(B43_OFDM_RATE_48MB, IEEE80211_RATE_OFDM),
137         RATETAB_ENT(B43_OFDM_RATE_54MB, IEEE80211_RATE_OFDM),
138 };
139
140 #define b43_a_ratetable         (__b43_ratetable + 4)
141 #define b43_a_ratetable_size    8
142 #define b43_b_ratetable         (__b43_ratetable + 0)
143 #define b43_b_ratetable_size    4
144 #define b43_g_ratetable         (__b43_ratetable + 0)
145 #define b43_g_ratetable_size    12
146
147 #define CHANTAB_ENT(_chanid, _freq) \
148         {                                                       \
149                 .chan   = (_chanid),                            \
150                 .freq   = (_freq),                              \
151                 .val    = (_chanid),                            \
152                 .flag   = IEEE80211_CHAN_W_SCAN |               \
153                           IEEE80211_CHAN_W_ACTIVE_SCAN |        \
154                           IEEE80211_CHAN_W_IBSS,                \
155                 .power_level    = 0xFF,                         \
156                 .antenna_max    = 0xFF,                         \
157         }
158 static struct ieee80211_channel b43_bg_chantable[] = {
159         CHANTAB_ENT(1, 2412),
160         CHANTAB_ENT(2, 2417),
161         CHANTAB_ENT(3, 2422),
162         CHANTAB_ENT(4, 2427),
163         CHANTAB_ENT(5, 2432),
164         CHANTAB_ENT(6, 2437),
165         CHANTAB_ENT(7, 2442),
166         CHANTAB_ENT(8, 2447),
167         CHANTAB_ENT(9, 2452),
168         CHANTAB_ENT(10, 2457),
169         CHANTAB_ENT(11, 2462),
170         CHANTAB_ENT(12, 2467),
171         CHANTAB_ENT(13, 2472),
172         CHANTAB_ENT(14, 2484),
173 };
174
175 #define b43_bg_chantable_size   ARRAY_SIZE(b43_bg_chantable)
176 static struct ieee80211_channel b43_a_chantable[] = {
177         CHANTAB_ENT(36, 5180),
178         CHANTAB_ENT(40, 5200),
179         CHANTAB_ENT(44, 5220),
180         CHANTAB_ENT(48, 5240),
181         CHANTAB_ENT(52, 5260),
182         CHANTAB_ENT(56, 5280),
183         CHANTAB_ENT(60, 5300),
184         CHANTAB_ENT(64, 5320),
185         CHANTAB_ENT(149, 5745),
186         CHANTAB_ENT(153, 5765),
187         CHANTAB_ENT(157, 5785),
188         CHANTAB_ENT(161, 5805),
189         CHANTAB_ENT(165, 5825),
190 };
191
192 #define b43_a_chantable_size    ARRAY_SIZE(b43_a_chantable)
193
194 static void b43_wireless_core_exit(struct b43_wldev *dev);
195 static int b43_wireless_core_init(struct b43_wldev *dev);
196 static void b43_wireless_core_stop(struct b43_wldev *dev);
197 static int b43_wireless_core_start(struct b43_wldev *dev);
198
199 static int b43_ratelimit(struct b43_wl *wl)
200 {
201         if (!wl || !wl->current_dev)
202                 return 1;
203         if (b43_status(wl->current_dev) < B43_STAT_STARTED)
204                 return 1;
205         /* We are up and running.
206          * Ratelimit the messages to avoid DoS over the net. */
207         return net_ratelimit();
208 }
209
210 void b43info(struct b43_wl *wl, const char *fmt, ...)
211 {
212         va_list args;
213
214         if (!b43_ratelimit(wl))
215                 return;
216         va_start(args, fmt);
217         printk(KERN_INFO "b43-%s: ",
218                (wl && wl->hw) ? wiphy_name(wl->hw->wiphy) : "wlan");
219         vprintk(fmt, args);
220         va_end(args);
221 }
222
223 void b43err(struct b43_wl *wl, const char *fmt, ...)
224 {
225         va_list args;
226
227         if (!b43_ratelimit(wl))
228                 return;
229         va_start(args, fmt);
230         printk(KERN_ERR "b43-%s ERROR: ",
231                (wl && wl->hw) ? wiphy_name(wl->hw->wiphy) : "wlan");
232         vprintk(fmt, args);
233         va_end(args);
234 }
235
236 void b43warn(struct b43_wl *wl, const char *fmt, ...)
237 {
238         va_list args;
239
240         if (!b43_ratelimit(wl))
241                 return;
242         va_start(args, fmt);
243         printk(KERN_WARNING "b43-%s warning: ",
244                (wl && wl->hw) ? wiphy_name(wl->hw->wiphy) : "wlan");
245         vprintk(fmt, args);
246         va_end(args);
247 }
248
249 #if B43_DEBUG
250 void b43dbg(struct b43_wl *wl, const char *fmt, ...)
251 {
252         va_list args;
253
254         va_start(args, fmt);
255         printk(KERN_DEBUG "b43-%s debug: ",
256                (wl && wl->hw) ? wiphy_name(wl->hw->wiphy) : "wlan");
257         vprintk(fmt, args);
258         va_end(args);
259 }
260 #endif /* DEBUG */
261
262 static void b43_ram_write(struct b43_wldev *dev, u16 offset, u32 val)
263 {
264         u32 macctl;
265
266         B43_WARN_ON(offset % 4 != 0);
267
268         macctl = b43_read32(dev, B43_MMIO_MACCTL);
269         if (macctl & B43_MACCTL_BE)
270                 val = swab32(val);
271
272         b43_write32(dev, B43_MMIO_RAM_CONTROL, offset);
273         mmiowb();
274         b43_write32(dev, B43_MMIO_RAM_DATA, val);
275 }
276
277 static inline
278     void b43_shm_control_word(struct b43_wldev *dev, u16 routing, u16 offset)
279 {
280         u32 control;
281
282         /* "offset" is the WORD offset. */
283
284         control = routing;
285         control <<= 16;
286         control |= offset;
287         b43_write32(dev, B43_MMIO_SHM_CONTROL, control);
288 }
289
290 u32 b43_shm_read32(struct b43_wldev *dev, u16 routing, u16 offset)
291 {
292         u32 ret;
293
294         if (routing == B43_SHM_SHARED) {
295                 B43_WARN_ON(offset & 0x0001);
296                 if (offset & 0x0003) {
297                         /* Unaligned access */
298                         b43_shm_control_word(dev, routing, offset >> 2);
299                         ret = b43_read16(dev, B43_MMIO_SHM_DATA_UNALIGNED);
300                         ret <<= 16;
301                         b43_shm_control_word(dev, routing, (offset >> 2) + 1);
302                         ret |= b43_read16(dev, B43_MMIO_SHM_DATA);
303
304                         return ret;
305                 }
306                 offset >>= 2;
307         }
308         b43_shm_control_word(dev, routing, offset);
309         ret = b43_read32(dev, B43_MMIO_SHM_DATA);
310
311         return ret;
312 }
313
314 u16 b43_shm_read16(struct b43_wldev * dev, u16 routing, u16 offset)
315 {
316         u16 ret;
317
318         if (routing == B43_SHM_SHARED) {
319                 B43_WARN_ON(offset & 0x0001);
320                 if (offset & 0x0003) {
321                         /* Unaligned access */
322                         b43_shm_control_word(dev, routing, offset >> 2);
323                         ret = b43_read16(dev, B43_MMIO_SHM_DATA_UNALIGNED);
324
325                         return ret;
326                 }
327                 offset >>= 2;
328         }
329         b43_shm_control_word(dev, routing, offset);
330         ret = b43_read16(dev, B43_MMIO_SHM_DATA);
331
332         return ret;
333 }
334
335 void b43_shm_write32(struct b43_wldev *dev, u16 routing, u16 offset, u32 value)
336 {
337         if (routing == B43_SHM_SHARED) {
338                 B43_WARN_ON(offset & 0x0001);
339                 if (offset & 0x0003) {
340                         /* Unaligned access */
341                         b43_shm_control_word(dev, routing, offset >> 2);
342                         mmiowb();
343                         b43_write16(dev, B43_MMIO_SHM_DATA_UNALIGNED,
344                                     (value >> 16) & 0xffff);
345                         mmiowb();
346                         b43_shm_control_word(dev, routing, (offset >> 2) + 1);
347                         mmiowb();
348                         b43_write16(dev, B43_MMIO_SHM_DATA, value & 0xffff);
349                         return;
350                 }
351                 offset >>= 2;
352         }
353         b43_shm_control_word(dev, routing, offset);
354         mmiowb();
355         b43_write32(dev, B43_MMIO_SHM_DATA, value);
356 }
357
358 void b43_shm_write16(struct b43_wldev *dev, u16 routing, u16 offset, u16 value)
359 {
360         if (routing == B43_SHM_SHARED) {
361                 B43_WARN_ON(offset & 0x0001);
362                 if (offset & 0x0003) {
363                         /* Unaligned access */
364                         b43_shm_control_word(dev, routing, offset >> 2);
365                         mmiowb();
366                         b43_write16(dev, B43_MMIO_SHM_DATA_UNALIGNED, value);
367                         return;
368                 }
369                 offset >>= 2;
370         }
371         b43_shm_control_word(dev, routing, offset);
372         mmiowb();
373         b43_write16(dev, B43_MMIO_SHM_DATA, value);
374 }
375
376 /* Read HostFlags */
377 u32 b43_hf_read(struct b43_wldev * dev)
378 {
379         u32 ret;
380
381         ret = b43_shm_read16(dev, B43_SHM_SHARED, B43_SHM_SH_HOSTFHI);
382         ret <<= 16;
383         ret |= b43_shm_read16(dev, B43_SHM_SHARED, B43_SHM_SH_HOSTFLO);
384
385         return ret;
386 }
387
388 /* Write HostFlags */
389 void b43_hf_write(struct b43_wldev *dev, u32 value)
390 {
391         b43_shm_write16(dev, B43_SHM_SHARED,
392                         B43_SHM_SH_HOSTFLO, (value & 0x0000FFFF));
393         b43_shm_write16(dev, B43_SHM_SHARED,
394                         B43_SHM_SH_HOSTFHI, ((value & 0xFFFF0000) >> 16));
395 }
396
397 void b43_tsf_read(struct b43_wldev *dev, u64 * tsf)
398 {
399         /* We need to be careful. As we read the TSF from multiple
400          * registers, we should take care of register overflows.
401          * In theory, the whole tsf read process should be atomic.
402          * We try to be atomic here, by restaring the read process,
403          * if any of the high registers changed (overflew).
404          */
405         if (dev->dev->id.revision >= 3) {
406                 u32 low, high, high2;
407
408                 do {
409                         high = b43_read32(dev, B43_MMIO_REV3PLUS_TSF_HIGH);
410                         low = b43_read32(dev, B43_MMIO_REV3PLUS_TSF_LOW);
411                         high2 = b43_read32(dev, B43_MMIO_REV3PLUS_TSF_HIGH);
412                 } while (unlikely(high != high2));
413
414                 *tsf = high;
415                 *tsf <<= 32;
416                 *tsf |= low;
417         } else {
418                 u64 tmp;
419                 u16 v0, v1, v2, v3;
420                 u16 test1, test2, test3;
421
422                 do {
423                         v3 = b43_read16(dev, B43_MMIO_TSF_3);
424                         v2 = b43_read16(dev, B43_MMIO_TSF_2);
425                         v1 = b43_read16(dev, B43_MMIO_TSF_1);
426                         v0 = b43_read16(dev, B43_MMIO_TSF_0);
427
428                         test3 = b43_read16(dev, B43_MMIO_TSF_3);
429                         test2 = b43_read16(dev, B43_MMIO_TSF_2);
430                         test1 = b43_read16(dev, B43_MMIO_TSF_1);
431                 } while (v3 != test3 || v2 != test2 || v1 != test1);
432
433                 *tsf = v3;
434                 *tsf <<= 48;
435                 tmp = v2;
436                 tmp <<= 32;
437                 *tsf |= tmp;
438                 tmp = v1;
439                 tmp <<= 16;
440                 *tsf |= tmp;
441                 *tsf |= v0;
442         }
443 }
444
445 static void b43_time_lock(struct b43_wldev *dev)
446 {
447         u32 macctl;
448
449         macctl = b43_read32(dev, B43_MMIO_MACCTL);
450         macctl |= B43_MACCTL_TBTTHOLD;
451         b43_write32(dev, B43_MMIO_MACCTL, macctl);
452         /* Commit the write */
453         b43_read32(dev, B43_MMIO_MACCTL);
454 }
455
456 static void b43_time_unlock(struct b43_wldev *dev)
457 {
458         u32 macctl;
459
460         macctl = b43_read32(dev, B43_MMIO_MACCTL);
461         macctl &= ~B43_MACCTL_TBTTHOLD;
462         b43_write32(dev, B43_MMIO_MACCTL, macctl);
463         /* Commit the write */
464         b43_read32(dev, B43_MMIO_MACCTL);
465 }
466
467 static void b43_tsf_write_locked(struct b43_wldev *dev, u64 tsf)
468 {
469         /* Be careful with the in-progress timer.
470          * First zero out the low register, so we have a full
471          * register-overflow duration to complete the operation.
472          */
473         if (dev->dev->id.revision >= 3) {
474                 u32 lo = (tsf & 0x00000000FFFFFFFFULL);
475                 u32 hi = (tsf & 0xFFFFFFFF00000000ULL) >> 32;
476
477                 b43_write32(dev, B43_MMIO_REV3PLUS_TSF_LOW, 0);
478                 mmiowb();
479                 b43_write32(dev, B43_MMIO_REV3PLUS_TSF_HIGH, hi);
480                 mmiowb();
481                 b43_write32(dev, B43_MMIO_REV3PLUS_TSF_LOW, lo);
482         } else {
483                 u16 v0 = (tsf & 0x000000000000FFFFULL);
484                 u16 v1 = (tsf & 0x00000000FFFF0000ULL) >> 16;
485                 u16 v2 = (tsf & 0x0000FFFF00000000ULL) >> 32;
486                 u16 v3 = (tsf & 0xFFFF000000000000ULL) >> 48;
487
488                 b43_write16(dev, B43_MMIO_TSF_0, 0);
489                 mmiowb();
490                 b43_write16(dev, B43_MMIO_TSF_3, v3);
491                 mmiowb();
492                 b43_write16(dev, B43_MMIO_TSF_2, v2);
493                 mmiowb();
494                 b43_write16(dev, B43_MMIO_TSF_1, v1);
495                 mmiowb();
496                 b43_write16(dev, B43_MMIO_TSF_0, v0);
497         }
498 }
499
500 void b43_tsf_write(struct b43_wldev *dev, u64 tsf)
501 {
502         b43_time_lock(dev);
503         b43_tsf_write_locked(dev, tsf);
504         b43_time_unlock(dev);
505 }
506
507 static
508 void b43_macfilter_set(struct b43_wldev *dev, u16 offset, const u8 * mac)
509 {
510         static const u8 zero_addr[ETH_ALEN] = { 0 };
511         u16 data;
512
513         if (!mac)
514                 mac = zero_addr;
515
516         offset |= 0x0020;
517         b43_write16(dev, B43_MMIO_MACFILTER_CONTROL, offset);
518
519         data = mac[0];
520         data |= mac[1] << 8;
521         b43_write16(dev, B43_MMIO_MACFILTER_DATA, data);
522         data = mac[2];
523         data |= mac[3] << 8;
524         b43_write16(dev, B43_MMIO_MACFILTER_DATA, data);
525         data = mac[4];
526         data |= mac[5] << 8;
527         b43_write16(dev, B43_MMIO_MACFILTER_DATA, data);
528 }
529
530 static void b43_write_mac_bssid_templates(struct b43_wldev *dev)
531 {
532         const u8 *mac;
533         const u8 *bssid;
534         u8 mac_bssid[ETH_ALEN * 2];
535         int i;
536         u32 tmp;
537
538         bssid = dev->wl->bssid;
539         mac = dev->wl->mac_addr;
540
541         b43_macfilter_set(dev, B43_MACFILTER_BSSID, bssid);
542
543         memcpy(mac_bssid, mac, ETH_ALEN);
544         memcpy(mac_bssid + ETH_ALEN, bssid, ETH_ALEN);
545
546         /* Write our MAC address and BSSID to template ram */
547         for (i = 0; i < ARRAY_SIZE(mac_bssid); i += sizeof(u32)) {
548                 tmp = (u32) (mac_bssid[i + 0]);
549                 tmp |= (u32) (mac_bssid[i + 1]) << 8;
550                 tmp |= (u32) (mac_bssid[i + 2]) << 16;
551                 tmp |= (u32) (mac_bssid[i + 3]) << 24;
552                 b43_ram_write(dev, 0x20 + i, tmp);
553         }
554 }
555
556 static void b43_upload_card_macaddress(struct b43_wldev *dev)
557 {
558         b43_write_mac_bssid_templates(dev);
559         b43_macfilter_set(dev, B43_MACFILTER_SELF, dev->wl->mac_addr);
560 }
561
562 static void b43_set_slot_time(struct b43_wldev *dev, u16 slot_time)
563 {
564         /* slot_time is in usec. */
565         if (dev->phy.type != B43_PHYTYPE_G)
566                 return;
567         b43_write16(dev, 0x684, 510 + slot_time);
568         b43_shm_write16(dev, B43_SHM_SHARED, 0x0010, slot_time);
569 }
570
571 static void b43_short_slot_timing_enable(struct b43_wldev *dev)
572 {
573         b43_set_slot_time(dev, 9);
574         dev->short_slot = 1;
575 }
576
577 static void b43_short_slot_timing_disable(struct b43_wldev *dev)
578 {
579         b43_set_slot_time(dev, 20);
580         dev->short_slot = 0;
581 }
582
583 /* Enable a Generic IRQ. "mask" is the mask of which IRQs to enable.
584  * Returns the _previously_ enabled IRQ mask.
585  */
586 static inline u32 b43_interrupt_enable(struct b43_wldev *dev, u32 mask)
587 {
588         u32 old_mask;
589
590         old_mask = b43_read32(dev, B43_MMIO_GEN_IRQ_MASK);
591         b43_write32(dev, B43_MMIO_GEN_IRQ_MASK, old_mask | mask);
592
593         return old_mask;
594 }
595
596 /* Disable a Generic IRQ. "mask" is the mask of which IRQs to disable.
597  * Returns the _previously_ enabled IRQ mask.
598  */
599 static inline u32 b43_interrupt_disable(struct b43_wldev *dev, u32 mask)
600 {
601         u32 old_mask;
602
603         old_mask = b43_read32(dev, B43_MMIO_GEN_IRQ_MASK);
604         b43_write32(dev, B43_MMIO_GEN_IRQ_MASK, old_mask & ~mask);
605
606         return old_mask;
607 }
608
609 /* Synchronize IRQ top- and bottom-half.
610  * IRQs must be masked before calling this.
611  * This must not be called with the irq_lock held.
612  */
613 static void b43_synchronize_irq(struct b43_wldev *dev)
614 {
615         synchronize_irq(dev->dev->irq);
616         tasklet_kill(&dev->isr_tasklet);
617 }
618
619 /* DummyTransmission function, as documented on
620  * http://bcm-specs.sipsolutions.net/DummyTransmission
621  */
622 void b43_dummy_transmission(struct b43_wldev *dev)
623 {
624         struct b43_phy *phy = &dev->phy;
625         unsigned int i, max_loop;
626         u16 value;
627         u32 buffer[5] = {
628                 0x00000000,
629                 0x00D40000,
630                 0x00000000,
631                 0x01000000,
632                 0x00000000,
633         };
634
635         switch (phy->type) {
636         case B43_PHYTYPE_A:
637                 max_loop = 0x1E;
638                 buffer[0] = 0x000201CC;
639                 break;
640         case B43_PHYTYPE_B:
641         case B43_PHYTYPE_G:
642                 max_loop = 0xFA;
643                 buffer[0] = 0x000B846E;
644                 break;
645         default:
646                 B43_WARN_ON(1);
647                 return;
648         }
649
650         for (i = 0; i < 5; i++)
651                 b43_ram_write(dev, i * 4, buffer[i]);
652
653         /* Commit writes */
654         b43_read32(dev, B43_MMIO_MACCTL);
655
656         b43_write16(dev, 0x0568, 0x0000);
657         b43_write16(dev, 0x07C0, 0x0000);
658         value = ((phy->type == B43_PHYTYPE_A) ? 1 : 0);
659         b43_write16(dev, 0x050C, value);
660         b43_write16(dev, 0x0508, 0x0000);
661         b43_write16(dev, 0x050A, 0x0000);
662         b43_write16(dev, 0x054C, 0x0000);
663         b43_write16(dev, 0x056A, 0x0014);
664         b43_write16(dev, 0x0568, 0x0826);
665         b43_write16(dev, 0x0500, 0x0000);
666         b43_write16(dev, 0x0502, 0x0030);
667
668         if (phy->radio_ver == 0x2050 && phy->radio_rev <= 0x5)
669                 b43_radio_write16(dev, 0x0051, 0x0017);
670         for (i = 0x00; i < max_loop; i++) {
671                 value = b43_read16(dev, 0x050E);
672                 if (value & 0x0080)
673                         break;
674                 udelay(10);
675         }
676         for (i = 0x00; i < 0x0A; i++) {
677                 value = b43_read16(dev, 0x050E);
678                 if (value & 0x0400)
679                         break;
680                 udelay(10);
681         }
682         for (i = 0x00; i < 0x0A; i++) {
683                 value = b43_read16(dev, 0x0690);
684                 if (!(value & 0x0100))
685                         break;
686                 udelay(10);
687         }
688         if (phy->radio_ver == 0x2050 && phy->radio_rev <= 0x5)
689                 b43_radio_write16(dev, 0x0051, 0x0037);
690 }
691
692 static void key_write(struct b43_wldev *dev,
693                       u8 index, u8 algorithm, const u8 * key)
694 {
695         unsigned int i;
696         u32 offset;
697         u16 value;
698         u16 kidx;
699
700         /* Key index/algo block */
701         kidx = b43_kidx_to_fw(dev, index);
702         value = ((kidx << 4) | algorithm);
703         b43_shm_write16(dev, B43_SHM_SHARED,
704                         B43_SHM_SH_KEYIDXBLOCK + (kidx * 2), value);
705
706         /* Write the key to the Key Table Pointer offset */
707         offset = dev->ktp + (index * B43_SEC_KEYSIZE);
708         for (i = 0; i < B43_SEC_KEYSIZE; i += 2) {
709                 value = key[i];
710                 value |= (u16) (key[i + 1]) << 8;
711                 b43_shm_write16(dev, B43_SHM_SHARED, offset + i, value);
712         }
713 }
714
715 static void keymac_write(struct b43_wldev *dev, u8 index, const u8 * addr)
716 {
717         u32 addrtmp[2] = { 0, 0, };
718         u8 per_sta_keys_start = 8;
719
720         if (b43_new_kidx_api(dev))
721                 per_sta_keys_start = 4;
722
723         B43_WARN_ON(index < per_sta_keys_start);
724         /* We have two default TX keys and possibly two default RX keys.
725          * Physical mac 0 is mapped to physical key 4 or 8, depending
726          * on the firmware version.
727          * So we must adjust the index here.
728          */
729         index -= per_sta_keys_start;
730
731         if (addr) {
732                 addrtmp[0] = addr[0];
733                 addrtmp[0] |= ((u32) (addr[1]) << 8);
734                 addrtmp[0] |= ((u32) (addr[2]) << 16);
735                 addrtmp[0] |= ((u32) (addr[3]) << 24);
736                 addrtmp[1] = addr[4];
737                 addrtmp[1] |= ((u32) (addr[5]) << 8);
738         }
739
740         if (dev->dev->id.revision >= 5) {
741                 /* Receive match transmitter address mechanism */
742                 b43_shm_write32(dev, B43_SHM_RCMTA,
743                                 (index * 2) + 0, addrtmp[0]);
744                 b43_shm_write16(dev, B43_SHM_RCMTA,
745                                 (index * 2) + 1, addrtmp[1]);
746         } else {
747                 /* RXE (Receive Engine) and
748                  * PSM (Programmable State Machine) mechanism
749                  */
750                 if (index < 8) {
751                         /* TODO write to RCM 16, 19, 22 and 25 */
752                 } else {
753                         b43_shm_write32(dev, B43_SHM_SHARED,
754                                         B43_SHM_SH_PSM + (index * 6) + 0,
755                                         addrtmp[0]);
756                         b43_shm_write16(dev, B43_SHM_SHARED,
757                                         B43_SHM_SH_PSM + (index * 6) + 4,
758                                         addrtmp[1]);
759                 }
760         }
761 }
762
763 static void do_key_write(struct b43_wldev *dev,
764                          u8 index, u8 algorithm,
765                          const u8 * key, size_t key_len, const u8 * mac_addr)
766 {
767         u8 buf[B43_SEC_KEYSIZE] = { 0, };
768         u8 per_sta_keys_start = 8;
769
770         if (b43_new_kidx_api(dev))
771                 per_sta_keys_start = 4;
772
773         B43_WARN_ON(index >= dev->max_nr_keys);
774         B43_WARN_ON(key_len > B43_SEC_KEYSIZE);
775
776         if (index >= per_sta_keys_start)
777                 keymac_write(dev, index, NULL); /* First zero out mac. */
778         if (key)
779                 memcpy(buf, key, key_len);
780         key_write(dev, index, algorithm, buf);
781         if (index >= per_sta_keys_start)
782                 keymac_write(dev, index, mac_addr);
783
784         dev->key[index].algorithm = algorithm;
785 }
786
787 static int b43_key_write(struct b43_wldev *dev,
788                          int index, u8 algorithm,
789                          const u8 * key, size_t key_len,
790                          const u8 * mac_addr,
791                          struct ieee80211_key_conf *keyconf)
792 {
793         int i;
794         int sta_keys_start;
795
796         if (key_len > B43_SEC_KEYSIZE)
797                 return -EINVAL;
798         for (i = 0; i < dev->max_nr_keys; i++) {
799                 /* Check that we don't already have this key. */
800                 B43_WARN_ON(dev->key[i].keyconf == keyconf);
801         }
802         if (index < 0) {
803                 /* Either pairwise key or address is 00:00:00:00:00:00
804                  * for transmit-only keys. Search the index. */
805                 if (b43_new_kidx_api(dev))
806                         sta_keys_start = 4;
807                 else
808                         sta_keys_start = 8;
809                 for (i = sta_keys_start; i < dev->max_nr_keys; i++) {
810                         if (!dev->key[i].keyconf) {
811                                 /* found empty */
812                                 index = i;
813                                 break;
814                         }
815                 }
816                 if (index < 0) {
817                         b43err(dev->wl, "Out of hardware key memory\n");
818                         return -ENOSPC;
819                 }
820         } else
821                 B43_WARN_ON(index > 3);
822
823         do_key_write(dev, index, algorithm, key, key_len, mac_addr);
824         if ((index <= 3) && !b43_new_kidx_api(dev)) {
825                 /* Default RX key */
826                 B43_WARN_ON(mac_addr);
827                 do_key_write(dev, index + 4, algorithm, key, key_len, NULL);
828         }
829         keyconf->hw_key_idx = index;
830         dev->key[index].keyconf = keyconf;
831
832         return 0;
833 }
834
835 static int b43_key_clear(struct b43_wldev *dev, int index)
836 {
837         if (B43_WARN_ON((index < 0) || (index >= dev->max_nr_keys)))
838                 return -EINVAL;
839         do_key_write(dev, index, B43_SEC_ALGO_NONE,
840                      NULL, B43_SEC_KEYSIZE, NULL);
841         if ((index <= 3) && !b43_new_kidx_api(dev)) {
842                 do_key_write(dev, index + 4, B43_SEC_ALGO_NONE,
843                              NULL, B43_SEC_KEYSIZE, NULL);
844         }
845         dev->key[index].keyconf = NULL;
846
847         return 0;
848 }
849
850 static void b43_clear_keys(struct b43_wldev *dev)
851 {
852         int i;
853
854         for (i = 0; i < dev->max_nr_keys; i++)
855                 b43_key_clear(dev, i);
856 }
857
858 void b43_power_saving_ctl_bits(struct b43_wldev *dev, unsigned int ps_flags)
859 {
860         u32 macctl;
861         u16 ucstat;
862         bool hwps;
863         bool awake;
864         int i;
865
866         B43_WARN_ON((ps_flags & B43_PS_ENABLED) &&
867                     (ps_flags & B43_PS_DISABLED));
868         B43_WARN_ON((ps_flags & B43_PS_AWAKE) && (ps_flags & B43_PS_ASLEEP));
869
870         if (ps_flags & B43_PS_ENABLED) {
871                 hwps = 1;
872         } else if (ps_flags & B43_PS_DISABLED) {
873                 hwps = 0;
874         } else {
875                 //TODO: If powersave is not off and FIXME is not set and we are not in adhoc
876                 //      and thus is not an AP and we are associated, set bit 25
877         }
878         if (ps_flags & B43_PS_AWAKE) {
879                 awake = 1;
880         } else if (ps_flags & B43_PS_ASLEEP) {
881                 awake = 0;
882         } else {
883                 //TODO: If the device is awake or this is an AP, or we are scanning, or FIXME,
884                 //      or we are associated, or FIXME, or the latest PS-Poll packet sent was
885                 //      successful, set bit26
886         }
887
888 /* FIXME: For now we force awake-on and hwps-off */
889         hwps = 0;
890         awake = 1;
891
892         macctl = b43_read32(dev, B43_MMIO_MACCTL);
893         if (hwps)
894                 macctl |= B43_MACCTL_HWPS;
895         else
896                 macctl &= ~B43_MACCTL_HWPS;
897         if (awake)
898                 macctl |= B43_MACCTL_AWAKE;
899         else
900                 macctl &= ~B43_MACCTL_AWAKE;
901         b43_write32(dev, B43_MMIO_MACCTL, macctl);
902         /* Commit write */
903         b43_read32(dev, B43_MMIO_MACCTL);
904         if (awake && dev->dev->id.revision >= 5) {
905                 /* Wait for the microcode to wake up. */
906                 for (i = 0; i < 100; i++) {
907                         ucstat = b43_shm_read16(dev, B43_SHM_SHARED,
908                                                 B43_SHM_SH_UCODESTAT);
909                         if (ucstat != B43_SHM_SH_UCODESTAT_SLEEP)
910                                 break;
911                         udelay(10);
912                 }
913         }
914 }
915
916 /* Turn the Analog ON/OFF */
917 static void b43_switch_analog(struct b43_wldev *dev, int on)
918 {
919         b43_write16(dev, B43_MMIO_PHY0, on ? 0 : 0xF4);
920 }
921
922 void b43_wireless_core_reset(struct b43_wldev *dev, u32 flags)
923 {
924         u32 tmslow;
925         u32 macctl;
926
927         flags |= B43_TMSLOW_PHYCLKEN;
928         flags |= B43_TMSLOW_PHYRESET;
929         ssb_device_enable(dev->dev, flags);
930         msleep(2);              /* Wait for the PLL to turn on. */
931
932         /* Now take the PHY out of Reset again */
933         tmslow = ssb_read32(dev->dev, SSB_TMSLOW);
934         tmslow |= SSB_TMSLOW_FGC;
935         tmslow &= ~B43_TMSLOW_PHYRESET;
936         ssb_write32(dev->dev, SSB_TMSLOW, tmslow);
937         ssb_read32(dev->dev, SSB_TMSLOW);       /* flush */
938         msleep(1);
939         tmslow &= ~SSB_TMSLOW_FGC;
940         ssb_write32(dev->dev, SSB_TMSLOW, tmslow);
941         ssb_read32(dev->dev, SSB_TMSLOW);       /* flush */
942         msleep(1);
943
944         /* Turn Analog ON */
945         b43_switch_analog(dev, 1);
946
947         macctl = b43_read32(dev, B43_MMIO_MACCTL);
948         macctl &= ~B43_MACCTL_GMODE;
949         if (flags & B43_TMSLOW_GMODE)
950                 macctl |= B43_MACCTL_GMODE;
951         macctl |= B43_MACCTL_IHR_ENABLED;
952         b43_write32(dev, B43_MMIO_MACCTL, macctl);
953 }
954
955 static void handle_irq_transmit_status(struct b43_wldev *dev)
956 {
957         u32 v0, v1;
958         u16 tmp;
959         struct b43_txstatus stat;
960
961         while (1) {
962                 v0 = b43_read32(dev, B43_MMIO_XMITSTAT_0);
963                 if (!(v0 & 0x00000001))
964                         break;
965                 v1 = b43_read32(dev, B43_MMIO_XMITSTAT_1);
966
967                 stat.cookie = (v0 >> 16);
968                 stat.seq = (v1 & 0x0000FFFF);
969                 stat.phy_stat = ((v1 & 0x00FF0000) >> 16);
970                 tmp = (v0 & 0x0000FFFF);
971                 stat.frame_count = ((tmp & 0xF000) >> 12);
972                 stat.rts_count = ((tmp & 0x0F00) >> 8);
973                 stat.supp_reason = ((tmp & 0x001C) >> 2);
974                 stat.pm_indicated = !!(tmp & 0x0080);
975                 stat.intermediate = !!(tmp & 0x0040);
976                 stat.for_ampdu = !!(tmp & 0x0020);
977                 stat.acked = !!(tmp & 0x0002);
978
979                 b43_handle_txstatus(dev, &stat);
980         }
981 }
982
983 static void drain_txstatus_queue(struct b43_wldev *dev)
984 {
985         u32 dummy;
986
987         if (dev->dev->id.revision < 5)
988                 return;
989         /* Read all entries from the microcode TXstatus FIFO
990          * and throw them away.
991          */
992         while (1) {
993                 dummy = b43_read32(dev, B43_MMIO_XMITSTAT_0);
994                 if (!(dummy & 0x00000001))
995                         break;
996                 dummy = b43_read32(dev, B43_MMIO_XMITSTAT_1);
997         }
998 }
999
1000 static u32 b43_jssi_read(struct b43_wldev *dev)
1001 {
1002         u32 val = 0;
1003
1004         val = b43_shm_read16(dev, B43_SHM_SHARED, 0x08A);
1005         val <<= 16;
1006         val |= b43_shm_read16(dev, B43_SHM_SHARED, 0x088);
1007
1008         return val;
1009 }
1010
1011 static void b43_jssi_write(struct b43_wldev *dev, u32 jssi)
1012 {
1013         b43_shm_write16(dev, B43_SHM_SHARED, 0x088, (jssi & 0x0000FFFF));
1014         b43_shm_write16(dev, B43_SHM_SHARED, 0x08A, (jssi & 0xFFFF0000) >> 16);
1015 }
1016
1017 static void b43_generate_noise_sample(struct b43_wldev *dev)
1018 {
1019         b43_jssi_write(dev, 0x7F7F7F7F);
1020         b43_write32(dev, B43_MMIO_STATUS2_BITFIELD,
1021                     b43_read32(dev, B43_MMIO_STATUS2_BITFIELD)
1022                     | (1 << 4));
1023         B43_WARN_ON(dev->noisecalc.channel_at_start != dev->phy.channel);
1024 }
1025
1026 static void b43_calculate_link_quality(struct b43_wldev *dev)
1027 {
1028         /* Top half of Link Quality calculation. */
1029
1030         if (dev->noisecalc.calculation_running)
1031                 return;
1032         dev->noisecalc.channel_at_start = dev->phy.channel;
1033         dev->noisecalc.calculation_running = 1;
1034         dev->noisecalc.nr_samples = 0;
1035
1036         b43_generate_noise_sample(dev);
1037 }
1038
1039 static void handle_irq_noise(struct b43_wldev *dev)
1040 {
1041         struct b43_phy *phy = &dev->phy;
1042         u16 tmp;
1043         u8 noise[4];
1044         u8 i, j;
1045         s32 average;
1046
1047         /* Bottom half of Link Quality calculation. */
1048
1049         B43_WARN_ON(!dev->noisecalc.calculation_running);
1050         if (dev->noisecalc.channel_at_start != phy->channel)
1051                 goto drop_calculation;
1052         *((__le32 *)noise) = cpu_to_le32(b43_jssi_read(dev));
1053         if (noise[0] == 0x7F || noise[1] == 0x7F ||
1054             noise[2] == 0x7F || noise[3] == 0x7F)
1055                 goto generate_new;
1056
1057         /* Get the noise samples. */
1058         B43_WARN_ON(dev->noisecalc.nr_samples >= 8);
1059         i = dev->noisecalc.nr_samples;
1060         noise[0] = limit_value(noise[0], 0, ARRAY_SIZE(phy->nrssi_lt) - 1);
1061         noise[1] = limit_value(noise[1], 0, ARRAY_SIZE(phy->nrssi_lt) - 1);
1062         noise[2] = limit_value(noise[2], 0, ARRAY_SIZE(phy->nrssi_lt) - 1);
1063         noise[3] = limit_value(noise[3], 0, ARRAY_SIZE(phy->nrssi_lt) - 1);
1064         dev->noisecalc.samples[i][0] = phy->nrssi_lt[noise[0]];
1065         dev->noisecalc.samples[i][1] = phy->nrssi_lt[noise[1]];
1066         dev->noisecalc.samples[i][2] = phy->nrssi_lt[noise[2]];
1067         dev->noisecalc.samples[i][3] = phy->nrssi_lt[noise[3]];
1068         dev->noisecalc.nr_samples++;
1069         if (dev->noisecalc.nr_samples == 8) {
1070                 /* Calculate the Link Quality by the noise samples. */
1071                 average = 0;
1072                 for (i = 0; i < 8; i++) {
1073                         for (j = 0; j < 4; j++)
1074                                 average += dev->noisecalc.samples[i][j];
1075                 }
1076                 average /= (8 * 4);
1077                 average *= 125;
1078                 average += 64;
1079                 average /= 128;
1080                 tmp = b43_shm_read16(dev, B43_SHM_SHARED, 0x40C);
1081                 tmp = (tmp / 128) & 0x1F;
1082                 if (tmp >= 8)
1083                         average += 2;
1084                 else
1085                         average -= 25;
1086                 if (tmp == 8)
1087                         average -= 72;
1088                 else
1089                         average -= 48;
1090
1091                 dev->stats.link_noise = average;
1092               drop_calculation:
1093                 dev->noisecalc.calculation_running = 0;
1094                 return;
1095         }
1096       generate_new:
1097         b43_generate_noise_sample(dev);
1098 }
1099
1100 static void handle_irq_tbtt_indication(struct b43_wldev *dev)
1101 {
1102         if (b43_is_mode(dev->wl, IEEE80211_IF_TYPE_AP)) {
1103                 ///TODO: PS TBTT
1104         } else {
1105                 if (1 /*FIXME: the last PSpoll frame was sent successfully */ )
1106                         b43_power_saving_ctl_bits(dev, 0);
1107         }
1108         dev->reg124_set_0x4 = 0;
1109         if (b43_is_mode(dev->wl, IEEE80211_IF_TYPE_IBSS))
1110                 dev->reg124_set_0x4 = 1;
1111 }
1112
1113 static void handle_irq_atim_end(struct b43_wldev *dev)
1114 {
1115         if (!dev->reg124_set_0x4 /*FIXME rename this variable */ )
1116                 return;
1117         b43_write32(dev, B43_MMIO_STATUS2_BITFIELD,
1118                     b43_read32(dev, B43_MMIO_STATUS2_BITFIELD)
1119                     | 0x4);
1120 }
1121
1122 static void handle_irq_pmq(struct b43_wldev *dev)
1123 {
1124         u32 tmp;
1125
1126         //TODO: AP mode.
1127
1128         while (1) {
1129                 tmp = b43_read32(dev, B43_MMIO_PS_STATUS);
1130                 if (!(tmp & 0x00000008))
1131                         break;
1132         }
1133         /* 16bit write is odd, but correct. */
1134         b43_write16(dev, B43_MMIO_PS_STATUS, 0x0002);
1135 }
1136
1137 static void b43_write_template_common(struct b43_wldev *dev,
1138                                       const u8 * data, u16 size,
1139                                       u16 ram_offset,
1140                                       u16 shm_size_offset, u8 rate)
1141 {
1142         u32 i, tmp;
1143         struct b43_plcp_hdr4 plcp;
1144
1145         plcp.data = 0;
1146         b43_generate_plcp_hdr(&plcp, size + FCS_LEN, rate);
1147         b43_ram_write(dev, ram_offset, le32_to_cpu(plcp.data));
1148         ram_offset += sizeof(u32);
1149         /* The PLCP is 6 bytes long, but we only wrote 4 bytes, yet.
1150          * So leave the first two bytes of the next write blank.
1151          */
1152         tmp = (u32) (data[0]) << 16;
1153         tmp |= (u32) (data[1]) << 24;
1154         b43_ram_write(dev, ram_offset, tmp);
1155         ram_offset += sizeof(u32);
1156         for (i = 2; i < size; i += sizeof(u32)) {
1157                 tmp = (u32) (data[i + 0]);
1158                 if (i + 1 < size)
1159                         tmp |= (u32) (data[i + 1]) << 8;
1160                 if (i + 2 < size)
1161                         tmp |= (u32) (data[i + 2]) << 16;
1162                 if (i + 3 < size)
1163                         tmp |= (u32) (data[i + 3]) << 24;
1164                 b43_ram_write(dev, ram_offset + i - 2, tmp);
1165         }
1166         b43_shm_write16(dev, B43_SHM_SHARED, shm_size_offset,
1167                         size + sizeof(struct b43_plcp_hdr6));
1168 }
1169
1170 static void b43_write_beacon_template(struct b43_wldev *dev,
1171                                       u16 ram_offset,
1172                                       u16 shm_size_offset, u8 rate)
1173 {
1174         int len;
1175         const u8 *data;
1176
1177         B43_WARN_ON(!dev->cached_beacon);
1178         len = min((size_t) dev->cached_beacon->len,
1179                   0x200 - sizeof(struct b43_plcp_hdr6));
1180         data = (const u8 *)(dev->cached_beacon->data);
1181         b43_write_template_common(dev, data,
1182                                   len, ram_offset, shm_size_offset, rate);
1183 }
1184
1185 static void b43_write_probe_resp_plcp(struct b43_wldev *dev,
1186                                       u16 shm_offset, u16 size, u8 rate)
1187 {
1188         struct b43_plcp_hdr4 plcp;
1189         u32 tmp;
1190         __le16 dur;
1191
1192         plcp.data = 0;
1193         b43_generate_plcp_hdr(&plcp, size + FCS_LEN, rate);
1194         dur = ieee80211_generic_frame_duration(dev->wl->hw,
1195                                                dev->wl->if_id, size,
1196                                                B43_RATE_TO_BASE100KBPS(rate));
1197         /* Write PLCP in two parts and timing for packet transfer */
1198         tmp = le32_to_cpu(plcp.data);
1199         b43_shm_write16(dev, B43_SHM_SHARED, shm_offset, tmp & 0xFFFF);
1200         b43_shm_write16(dev, B43_SHM_SHARED, shm_offset + 2, tmp >> 16);
1201         b43_shm_write16(dev, B43_SHM_SHARED, shm_offset + 6, le16_to_cpu(dur));
1202 }
1203
1204 /* Instead of using custom probe response template, this function
1205  * just patches custom beacon template by:
1206  * 1) Changing packet type
1207  * 2) Patching duration field
1208  * 3) Stripping TIM
1209  */
1210 static u8 *b43_generate_probe_resp(struct b43_wldev *dev,
1211                                    u16 * dest_size, u8 rate)
1212 {
1213         const u8 *src_data;
1214         u8 *dest_data;
1215         u16 src_size, elem_size, src_pos, dest_pos;
1216         __le16 dur;
1217         struct ieee80211_hdr *hdr;
1218
1219         B43_WARN_ON(!dev->cached_beacon);
1220         src_size = dev->cached_beacon->len;
1221         src_data = (const u8 *)dev->cached_beacon->data;
1222
1223         if (unlikely(src_size < 0x24)) {
1224                 b43dbg(dev->wl, "b43_generate_probe_resp: " "invalid beacon\n");
1225                 return NULL;
1226         }
1227
1228         dest_data = kmalloc(src_size, GFP_ATOMIC);
1229         if (unlikely(!dest_data))
1230                 return NULL;
1231
1232         /* 0x24 is offset of first variable-len Information-Element
1233          * in beacon frame.
1234          */
1235         memcpy(dest_data, src_data, 0x24);
1236         src_pos = dest_pos = 0x24;
1237         for (; src_pos < src_size - 2; src_pos += elem_size) {
1238                 elem_size = src_data[src_pos + 1] + 2;
1239                 if (src_data[src_pos] != 0x05) {        /* TIM */
1240                         memcpy(dest_data + dest_pos, src_data + src_pos,
1241                                elem_size);
1242                         dest_pos += elem_size;
1243                 }
1244         }
1245         *dest_size = dest_pos;
1246         hdr = (struct ieee80211_hdr *)dest_data;
1247
1248         /* Set the frame control. */
1249         hdr->frame_control = cpu_to_le16(IEEE80211_FTYPE_MGMT |
1250                                          IEEE80211_STYPE_PROBE_RESP);
1251         dur = ieee80211_generic_frame_duration(dev->wl->hw,
1252                                                dev->wl->if_id, *dest_size,
1253                                                B43_RATE_TO_BASE100KBPS(rate));
1254         hdr->duration_id = dur;
1255
1256         return dest_data;
1257 }
1258
1259 static void b43_write_probe_resp_template(struct b43_wldev *dev,
1260                                           u16 ram_offset,
1261                                           u16 shm_size_offset, u8 rate)
1262 {
1263         u8 *probe_resp_data;
1264         u16 size;
1265
1266         B43_WARN_ON(!dev->cached_beacon);
1267         size = dev->cached_beacon->len;
1268         probe_resp_data = b43_generate_probe_resp(dev, &size, rate);
1269         if (unlikely(!probe_resp_data))
1270                 return;
1271
1272         /* Looks like PLCP headers plus packet timings are stored for
1273          * all possible basic rates
1274          */
1275         b43_write_probe_resp_plcp(dev, 0x31A, size, B43_CCK_RATE_1MB);
1276         b43_write_probe_resp_plcp(dev, 0x32C, size, B43_CCK_RATE_2MB);
1277         b43_write_probe_resp_plcp(dev, 0x33E, size, B43_CCK_RATE_5MB);
1278         b43_write_probe_resp_plcp(dev, 0x350, size, B43_CCK_RATE_11MB);
1279
1280         size = min((size_t) size, 0x200 - sizeof(struct b43_plcp_hdr6));
1281         b43_write_template_common(dev, probe_resp_data,
1282                                   size, ram_offset, shm_size_offset, rate);
1283         kfree(probe_resp_data);
1284 }
1285
1286 static int b43_refresh_cached_beacon(struct b43_wldev *dev,
1287                                      struct sk_buff *beacon)
1288 {
1289         if (dev->cached_beacon)
1290                 kfree_skb(dev->cached_beacon);
1291         dev->cached_beacon = beacon;
1292
1293         return 0;
1294 }
1295
1296 static void b43_update_templates(struct b43_wldev *dev)
1297 {
1298         u32 status;
1299
1300         B43_WARN_ON(!dev->cached_beacon);
1301
1302         b43_write_beacon_template(dev, 0x68, 0x18, B43_CCK_RATE_1MB);
1303         b43_write_beacon_template(dev, 0x468, 0x1A, B43_CCK_RATE_1MB);
1304         b43_write_probe_resp_template(dev, 0x268, 0x4A, B43_CCK_RATE_11MB);
1305
1306         status = b43_read32(dev, B43_MMIO_STATUS2_BITFIELD);
1307         status |= 0x03;
1308         b43_write32(dev, B43_MMIO_STATUS2_BITFIELD, status);
1309 }
1310
1311 static void b43_refresh_templates(struct b43_wldev *dev, struct sk_buff *beacon)
1312 {
1313         int err;
1314
1315         err = b43_refresh_cached_beacon(dev, beacon);
1316         if (unlikely(err))
1317                 return;
1318         b43_update_templates(dev);
1319 }
1320
1321 static void b43_set_ssid(struct b43_wldev *dev, const u8 * ssid, u8 ssid_len)
1322 {
1323         u32 tmp;
1324         u16 i, len;
1325
1326         len = min((u16) ssid_len, (u16) 0x100);
1327         for (i = 0; i < len; i += sizeof(u32)) {
1328                 tmp = (u32) (ssid[i + 0]);
1329                 if (i + 1 < len)
1330                         tmp |= (u32) (ssid[i + 1]) << 8;
1331                 if (i + 2 < len)
1332                         tmp |= (u32) (ssid[i + 2]) << 16;
1333                 if (i + 3 < len)
1334                         tmp |= (u32) (ssid[i + 3]) << 24;
1335                 b43_shm_write32(dev, B43_SHM_SHARED, 0x380 + i, tmp);
1336         }
1337         b43_shm_write16(dev, B43_SHM_SHARED, 0x48, len);
1338 }
1339
1340 static void b43_set_beacon_int(struct b43_wldev *dev, u16 beacon_int)
1341 {
1342         b43_time_lock(dev);
1343         if (dev->dev->id.revision >= 3) {
1344                 b43_write32(dev, 0x188, (beacon_int << 16));
1345         } else {
1346                 b43_write16(dev, 0x606, (beacon_int >> 6));
1347                 b43_write16(dev, 0x610, beacon_int);
1348         }
1349         b43_time_unlock(dev);
1350 }
1351
1352 static void handle_irq_beacon(struct b43_wldev *dev)
1353 {
1354         u32 status;
1355
1356         if (!b43_is_mode(dev->wl, IEEE80211_IF_TYPE_AP))
1357                 return;
1358
1359         dev->irq_savedstate &= ~B43_IRQ_BEACON;
1360         status = b43_read32(dev, B43_MMIO_STATUS2_BITFIELD);
1361
1362         if (!dev->cached_beacon || ((status & 0x1) && (status & 0x2))) {
1363                 /* ACK beacon IRQ. */
1364                 b43_write32(dev, B43_MMIO_GEN_IRQ_REASON, B43_IRQ_BEACON);
1365                 dev->irq_savedstate |= B43_IRQ_BEACON;
1366                 if (dev->cached_beacon)
1367                         kfree_skb(dev->cached_beacon);
1368                 dev->cached_beacon = NULL;
1369                 return;
1370         }
1371         if (!(status & 0x1)) {
1372                 b43_write_beacon_template(dev, 0x68, 0x18, B43_CCK_RATE_1MB);
1373                 status |= 0x1;
1374                 b43_write32(dev, B43_MMIO_STATUS2_BITFIELD, status);
1375         }
1376         if (!(status & 0x2)) {
1377                 b43_write_beacon_template(dev, 0x468, 0x1A, B43_CCK_RATE_1MB);
1378                 status |= 0x2;
1379                 b43_write32(dev, B43_MMIO_STATUS2_BITFIELD, status);
1380         }
1381 }
1382
1383 static void handle_irq_ucode_debug(struct b43_wldev *dev)
1384 {
1385         //TODO
1386 }
1387
1388 /* Interrupt handler bottom-half */
1389 static void b43_interrupt_tasklet(struct b43_wldev *dev)
1390 {
1391         u32 reason;
1392         u32 dma_reason[ARRAY_SIZE(dev->dma_reason)];
1393         u32 merged_dma_reason = 0;
1394         int i, activity = 0;
1395         unsigned long flags;
1396
1397         spin_lock_irqsave(&dev->wl->irq_lock, flags);
1398
1399         B43_WARN_ON(b43_status(dev) != B43_STAT_STARTED);
1400
1401         reason = dev->irq_reason;
1402         for (i = 0; i < ARRAY_SIZE(dma_reason); i++) {
1403                 dma_reason[i] = dev->dma_reason[i];
1404                 merged_dma_reason |= dma_reason[i];
1405         }
1406
1407         if (unlikely(reason & B43_IRQ_MAC_TXERR))
1408                 b43err(dev->wl, "MAC transmission error\n");
1409
1410         if (unlikely(reason & B43_IRQ_PHY_TXERR))
1411                 b43err(dev->wl, "PHY transmission error\n");
1412
1413         if (unlikely(merged_dma_reason & (B43_DMAIRQ_FATALMASK |
1414                                           B43_DMAIRQ_NONFATALMASK))) {
1415                 if (merged_dma_reason & B43_DMAIRQ_FATALMASK) {
1416                         b43err(dev->wl, "Fatal DMA error: "
1417                                "0x%08X, 0x%08X, 0x%08X, "
1418                                "0x%08X, 0x%08X, 0x%08X\n",
1419                                dma_reason[0], dma_reason[1],
1420                                dma_reason[2], dma_reason[3],
1421                                dma_reason[4], dma_reason[5]);
1422                         b43_controller_restart(dev, "DMA error");
1423                         mmiowb();
1424                         spin_unlock_irqrestore(&dev->wl->irq_lock, flags);
1425                         return;
1426                 }
1427                 if (merged_dma_reason & B43_DMAIRQ_NONFATALMASK) {
1428                         b43err(dev->wl, "DMA error: "
1429                                "0x%08X, 0x%08X, 0x%08X, "
1430                                "0x%08X, 0x%08X, 0x%08X\n",
1431                                dma_reason[0], dma_reason[1],
1432                                dma_reason[2], dma_reason[3],
1433                                dma_reason[4], dma_reason[5]);
1434                 }
1435         }
1436
1437         if (unlikely(reason & B43_IRQ_UCODE_DEBUG))
1438                 handle_irq_ucode_debug(dev);
1439         if (reason & B43_IRQ_TBTT_INDI)
1440                 handle_irq_tbtt_indication(dev);
1441         if (reason & B43_IRQ_ATIM_END)
1442                 handle_irq_atim_end(dev);
1443         if (reason & B43_IRQ_BEACON)
1444                 handle_irq_beacon(dev);
1445         if (reason & B43_IRQ_PMQ)
1446                 handle_irq_pmq(dev);
1447         if (reason & B43_IRQ_TXFIFO_FLUSH_OK) ;
1448         /*TODO*/ if (reason & B43_IRQ_NOISESAMPLE_OK)
1449                 handle_irq_noise(dev);
1450
1451         /* Check the DMA reason registers for received data. */
1452         if (dma_reason[0] & B43_DMAIRQ_RX_DONE) {
1453                 if (b43_using_pio(dev))
1454                         b43_pio_rx(dev->pio.queue0);
1455                 else
1456                         b43_dma_rx(dev->dma.rx_ring0);
1457                 /* We intentionally don't set "activity" to 1, here. */
1458         }
1459         B43_WARN_ON(dma_reason[1] & B43_DMAIRQ_RX_DONE);
1460         B43_WARN_ON(dma_reason[2] & B43_DMAIRQ_RX_DONE);
1461         if (dma_reason[3] & B43_DMAIRQ_RX_DONE) {
1462                 if (b43_using_pio(dev))
1463                         b43_pio_rx(dev->pio.queue3);
1464                 else
1465                         b43_dma_rx(dev->dma.rx_ring3);
1466                 activity = 1;
1467         }
1468         B43_WARN_ON(dma_reason[4] & B43_DMAIRQ_RX_DONE);
1469         B43_WARN_ON(dma_reason[5] & B43_DMAIRQ_RX_DONE);
1470
1471         if (reason & B43_IRQ_TX_OK) {
1472                 handle_irq_transmit_status(dev);
1473                 activity = 1;
1474                 //TODO: In AP mode, this also causes sending of powersave responses.
1475         }
1476
1477         if (!modparam_noleds)
1478                 b43_leds_update(dev, activity);
1479         b43_interrupt_enable(dev, dev->irq_savedstate);
1480         mmiowb();
1481         spin_unlock_irqrestore(&dev->wl->irq_lock, flags);
1482 }
1483
1484 static void pio_irq_workaround(struct b43_wldev *dev, u16 base, int queueidx)
1485 {
1486         u16 rxctl;
1487
1488         rxctl = b43_read16(dev, base + B43_PIO_RXCTL);
1489         if (rxctl & B43_PIO_RXCTL_DATAAVAILABLE)
1490                 dev->dma_reason[queueidx] |= B43_DMAIRQ_RX_DONE;
1491         else
1492                 dev->dma_reason[queueidx] &= ~B43_DMAIRQ_RX_DONE;
1493 }
1494
1495 static void b43_interrupt_ack(struct b43_wldev *dev, u32 reason)
1496 {
1497         if (b43_using_pio(dev) &&
1498             (dev->dev->id.revision < 3) &&
1499             (!(reason & B43_IRQ_PIO_WORKAROUND))) {
1500                 /* Apply a PIO specific workaround to the dma_reasons */
1501                 pio_irq_workaround(dev, B43_MMIO_PIO1_BASE, 0);
1502                 pio_irq_workaround(dev, B43_MMIO_PIO2_BASE, 1);
1503                 pio_irq_workaround(dev, B43_MMIO_PIO3_BASE, 2);
1504                 pio_irq_workaround(dev, B43_MMIO_PIO4_BASE, 3);
1505         }
1506
1507         b43_write32(dev, B43_MMIO_GEN_IRQ_REASON, reason);
1508
1509         b43_write32(dev, B43_MMIO_DMA0_REASON, dev->dma_reason[0]);
1510         b43_write32(dev, B43_MMIO_DMA1_REASON, dev->dma_reason[1]);
1511         b43_write32(dev, B43_MMIO_DMA2_REASON, dev->dma_reason[2]);
1512         b43_write32(dev, B43_MMIO_DMA3_REASON, dev->dma_reason[3]);
1513         b43_write32(dev, B43_MMIO_DMA4_REASON, dev->dma_reason[4]);
1514         b43_write32(dev, B43_MMIO_DMA5_REASON, dev->dma_reason[5]);
1515 }
1516
1517 /* Interrupt handler top-half */
1518 static irqreturn_t b43_interrupt_handler(int irq, void *dev_id)
1519 {
1520         irqreturn_t ret = IRQ_NONE;
1521         struct b43_wldev *dev = dev_id;
1522         u32 reason;
1523
1524         if (!dev)
1525                 return IRQ_NONE;
1526
1527         spin_lock(&dev->wl->irq_lock);
1528
1529         if (b43_status(dev) < B43_STAT_STARTED)
1530                 goto out;
1531         reason = b43_read32(dev, B43_MMIO_GEN_IRQ_REASON);
1532         if (reason == 0xffffffff)       /* shared IRQ */
1533                 goto out;
1534         ret = IRQ_HANDLED;
1535         reason &= b43_read32(dev, B43_MMIO_GEN_IRQ_MASK);
1536         if (!reason)
1537                 goto out;
1538
1539         dev->dma_reason[0] = b43_read32(dev, B43_MMIO_DMA0_REASON)
1540             & 0x0001DC00;
1541         dev->dma_reason[1] = b43_read32(dev, B43_MMIO_DMA1_REASON)
1542             & 0x0000DC00;
1543         dev->dma_reason[2] = b43_read32(dev, B43_MMIO_DMA2_REASON)
1544             & 0x0000DC00;
1545         dev->dma_reason[3] = b43_read32(dev, B43_MMIO_DMA3_REASON)
1546             & 0x0001DC00;
1547         dev->dma_reason[4] = b43_read32(dev, B43_MMIO_DMA4_REASON)
1548             & 0x0000DC00;
1549         dev->dma_reason[5] = b43_read32(dev, B43_MMIO_DMA5_REASON)
1550             & 0x0000DC00;
1551
1552         b43_interrupt_ack(dev, reason);
1553         /* disable all IRQs. They are enabled again in the bottom half. */
1554         dev->irq_savedstate = b43_interrupt_disable(dev, B43_IRQ_ALL);
1555         /* save the reason code and call our bottom half. */
1556         dev->irq_reason = reason;
1557         tasklet_schedule(&dev->isr_tasklet);
1558       out:
1559         mmiowb();
1560         spin_unlock(&dev->wl->irq_lock);
1561
1562         return ret;
1563 }
1564
1565 static void b43_release_firmware(struct b43_wldev *dev)
1566 {
1567         release_firmware(dev->fw.ucode);
1568         dev->fw.ucode = NULL;
1569         release_firmware(dev->fw.pcm);
1570         dev->fw.pcm = NULL;
1571         release_firmware(dev->fw.initvals);
1572         dev->fw.initvals = NULL;
1573         release_firmware(dev->fw.initvals_band);
1574         dev->fw.initvals_band = NULL;
1575 }
1576
1577 static void b43_print_fw_helptext(struct b43_wl *wl)
1578 {
1579         b43err(wl, "You must go to "
1580                "http://linuxwireless.org/en/users/Drivers/bcm43xx#devicefirmware "
1581                "and download the correct firmware (version 4).\n");
1582 }
1583
1584 static int do_request_fw(struct b43_wldev *dev,
1585                          const char *name,
1586                          const struct firmware **fw)
1587 {
1588         char path[sizeof(modparam_fwpostfix) + 32];
1589         struct b43_fw_header *hdr;
1590         u32 size;
1591         int err;
1592
1593         if (!name)
1594                 return 0;
1595
1596         snprintf(path, ARRAY_SIZE(path),
1597                  "b43%s/%s.fw",
1598                  modparam_fwpostfix, name);
1599         err = request_firmware(fw, path, dev->dev->dev);
1600         if (err) {
1601                 b43err(dev->wl, "Firmware file \"%s\" not found "
1602                        "or load failed.\n", path);
1603                 return err;
1604         }
1605         if ((*fw)->size < sizeof(struct b43_fw_header))
1606                 goto err_format;
1607         hdr = (struct b43_fw_header *)((*fw)->data);
1608         switch (hdr->type) {
1609         case B43_FW_TYPE_UCODE:
1610         case B43_FW_TYPE_PCM:
1611                 size = be32_to_cpu(hdr->size);
1612                 if (size != (*fw)->size - sizeof(struct b43_fw_header))
1613                         goto err_format;
1614                 /* fallthrough */
1615         case B43_FW_TYPE_IV:
1616                 if (hdr->ver != 1)
1617                         goto err_format;
1618                 break;
1619         default:
1620                 goto err_format;
1621         }
1622
1623         return err;
1624
1625 err_format:
1626         b43err(dev->wl, "Firmware file \"%s\" format error.\n", path);
1627         return -EPROTO;
1628 }
1629
1630 static int b43_request_firmware(struct b43_wldev *dev)
1631 {
1632         struct b43_firmware *fw = &dev->fw;
1633         const u8 rev = dev->dev->id.revision;
1634         const char *filename;
1635         u32 tmshigh;
1636         int err;
1637
1638         tmshigh = ssb_read32(dev->dev, SSB_TMSHIGH);
1639         if (!fw->ucode) {
1640                 if ((rev >= 5) && (rev <= 10))
1641                         filename = "ucode5";
1642                 else if ((rev >= 11) && (rev <= 12))
1643                         filename = "ucode11";
1644                 else if (rev >= 13)
1645                         filename = "ucode13";
1646                 else
1647                         goto err_no_ucode;
1648                 err = do_request_fw(dev, filename, &fw->ucode);
1649                 if (err)
1650                         goto err_load;
1651         }
1652         if (!fw->pcm) {
1653                 if ((rev >= 5) && (rev <= 10))
1654                         filename = "pcm5";
1655                 else if (rev >= 11)
1656                         filename = NULL;
1657                 else
1658                         goto err_no_pcm;
1659                 err = do_request_fw(dev, filename, &fw->pcm);
1660                 if (err)
1661                         goto err_load;
1662         }
1663         if (!fw->initvals) {
1664                 switch (dev->phy.type) {
1665                 case B43_PHYTYPE_A:
1666                         if ((rev >= 5) && (rev <= 10)) {
1667                                 if (tmshigh & B43_TMSHIGH_GPHY)
1668                                         filename = "a0g1initvals5";
1669                                 else
1670                                         filename = "a0g0initvals5";
1671                         } else
1672                                 goto err_no_initvals;
1673                         break;
1674                 case B43_PHYTYPE_G:
1675                         if ((rev >= 5) && (rev <= 10))
1676                                 filename = "b0g0initvals5";
1677                         else if (rev >= 13)
1678                                 filename = "lp0initvals13";
1679                         else
1680                                 goto err_no_initvals;
1681                         break;
1682                 default:
1683                         goto err_no_initvals;
1684                 }
1685                 err = do_request_fw(dev, filename, &fw->initvals);
1686                 if (err)
1687                         goto err_load;
1688         }
1689         if (!fw->initvals_band) {
1690                 switch (dev->phy.type) {
1691                 case B43_PHYTYPE_A:
1692                         if ((rev >= 5) && (rev <= 10)) {
1693                                 if (tmshigh & B43_TMSHIGH_GPHY)
1694                                         filename = "a0g1bsinitvals5";
1695                                 else
1696                                         filename = "a0g0bsinitvals5";
1697                         } else if (rev >= 11)
1698                                 filename = NULL;
1699                         else
1700                                 goto err_no_initvals;
1701                         break;
1702                 case B43_PHYTYPE_G:
1703                         if ((rev >= 5) && (rev <= 10))
1704                                 filename = "b0g0bsinitvals5";
1705                         else if (rev >= 11)
1706                                 filename = NULL;
1707                         else
1708                                 goto err_no_initvals;
1709                         break;
1710                 default:
1711                         goto err_no_initvals;
1712                 }
1713                 err = do_request_fw(dev, filename, &fw->initvals_band);
1714                 if (err)
1715                         goto err_load;
1716         }
1717
1718         return 0;
1719
1720 err_load:
1721         b43_print_fw_helptext(dev->wl);
1722         goto error;
1723
1724 err_no_ucode:
1725         err = -ENODEV;
1726         b43err(dev->wl, "No microcode available for core rev %u\n", rev);
1727         goto error;
1728
1729 err_no_pcm:
1730         err = -ENODEV;
1731         b43err(dev->wl, "No PCM available for core rev %u\n", rev);
1732         goto error;
1733
1734 err_no_initvals:
1735         err = -ENODEV;
1736         b43err(dev->wl, "No Initial Values firmware file for PHY %u, "
1737                "core rev %u\n", dev->phy.type, rev);
1738         goto error;
1739
1740 error:
1741         b43_release_firmware(dev);
1742         return err;
1743 }
1744
1745 static int b43_upload_microcode(struct b43_wldev *dev)
1746 {
1747         const size_t hdr_len = sizeof(struct b43_fw_header);
1748         const __be32 *data;
1749         unsigned int i, len;
1750         u16 fwrev, fwpatch, fwdate, fwtime;
1751         u32 tmp;
1752         int err = 0;
1753
1754         /* Upload Microcode. */
1755         data = (__be32 *) (dev->fw.ucode->data + hdr_len);
1756         len = (dev->fw.ucode->size - hdr_len) / sizeof(__be32);
1757         b43_shm_control_word(dev, B43_SHM_UCODE | B43_SHM_AUTOINC_W, 0x0000);
1758         for (i = 0; i < len; i++) {
1759                 b43_write32(dev, B43_MMIO_SHM_DATA, be32_to_cpu(data[i]));
1760                 udelay(10);
1761         }
1762
1763         if (dev->fw.pcm) {
1764                 /* Upload PCM data. */
1765                 data = (__be32 *) (dev->fw.pcm->data + hdr_len);
1766                 len = (dev->fw.pcm->size - hdr_len) / sizeof(__be32);
1767                 b43_shm_control_word(dev, B43_SHM_HW, 0x01EA);
1768                 b43_write32(dev, B43_MMIO_SHM_DATA, 0x00004000);
1769                 /* No need for autoinc bit in SHM_HW */
1770                 b43_shm_control_word(dev, B43_SHM_HW, 0x01EB);
1771                 for (i = 0; i < len; i++) {
1772                         b43_write32(dev, B43_MMIO_SHM_DATA, be32_to_cpu(data[i]));
1773                         udelay(10);
1774                 }
1775         }
1776
1777         b43_write32(dev, B43_MMIO_GEN_IRQ_REASON, B43_IRQ_ALL);
1778         b43_write32(dev, B43_MMIO_MACCTL,
1779                     B43_MACCTL_PSM_RUN |
1780                     B43_MACCTL_IHR_ENABLED | B43_MACCTL_INFRA);
1781
1782         /* Wait for the microcode to load and respond */
1783         i = 0;
1784         while (1) {
1785                 tmp = b43_read32(dev, B43_MMIO_GEN_IRQ_REASON);
1786                 if (tmp == B43_IRQ_MAC_SUSPENDED)
1787                         break;
1788                 i++;
1789                 if (i >= 50) {
1790                         b43err(dev->wl, "Microcode not responding\n");
1791                         b43_print_fw_helptext(dev->wl);
1792                         err = -ENODEV;
1793                         goto out;
1794                 }
1795                 udelay(10);
1796         }
1797         b43_read32(dev, B43_MMIO_GEN_IRQ_REASON);       /* dummy read */
1798
1799         /* Get and check the revisions. */
1800         fwrev = b43_shm_read16(dev, B43_SHM_SHARED, B43_SHM_SH_UCODEREV);
1801         fwpatch = b43_shm_read16(dev, B43_SHM_SHARED, B43_SHM_SH_UCODEPATCH);
1802         fwdate = b43_shm_read16(dev, B43_SHM_SHARED, B43_SHM_SH_UCODEDATE);
1803         fwtime = b43_shm_read16(dev, B43_SHM_SHARED, B43_SHM_SH_UCODETIME);
1804
1805         if (fwrev <= 0x128) {
1806                 b43err(dev->wl, "YOUR FIRMWARE IS TOO OLD. Firmware from "
1807                        "binary drivers older than version 4.x is unsupported. "
1808                        "You must upgrade your firmware files.\n");
1809                 b43_print_fw_helptext(dev->wl);
1810                 b43_write32(dev, B43_MMIO_MACCTL, 0);
1811                 err = -EOPNOTSUPP;
1812                 goto out;
1813         }
1814         b43dbg(dev->wl, "Loading firmware version %u.%u "
1815                "(20%.2i-%.2i-%.2i %.2i:%.2i:%.2i)\n",
1816                fwrev, fwpatch,
1817                (fwdate >> 12) & 0xF, (fwdate >> 8) & 0xF, fwdate & 0xFF,
1818                (fwtime >> 11) & 0x1F, (fwtime >> 5) & 0x3F, fwtime & 0x1F);
1819
1820         dev->fw.rev = fwrev;
1821         dev->fw.patch = fwpatch;
1822
1823       out:
1824         return err;
1825 }
1826
1827 static int b43_write_initvals(struct b43_wldev *dev,
1828                               const struct b43_iv *ivals,
1829                               size_t count,
1830                               size_t array_size)
1831 {
1832         const struct b43_iv *iv;
1833         u16 offset;
1834         size_t i;
1835         bool bit32;
1836
1837         BUILD_BUG_ON(sizeof(struct b43_iv) != 6);
1838         iv = ivals;
1839         for (i = 0; i < count; i++) {
1840                 if (array_size < sizeof(iv->offset_size))
1841                         goto err_format;
1842                 array_size -= sizeof(iv->offset_size);
1843                 offset = be16_to_cpu(iv->offset_size);
1844                 bit32 = !!(offset & B43_IV_32BIT);
1845                 offset &= B43_IV_OFFSET_MASK;
1846                 if (offset >= 0x1000)
1847                         goto err_format;
1848                 if (bit32) {
1849                         u32 value;
1850
1851                         if (array_size < sizeof(iv->data.d32))
1852                                 goto err_format;
1853                         array_size -= sizeof(iv->data.d32);
1854
1855                         value = be32_to_cpu(get_unaligned(&iv->data.d32));
1856                         b43_write32(dev, offset, value);
1857
1858                         iv = (const struct b43_iv *)((const uint8_t *)iv +
1859                                                         sizeof(__be16) +
1860                                                         sizeof(__be32));
1861                 } else {
1862                         u16 value;
1863
1864                         if (array_size < sizeof(iv->data.d16))
1865                                 goto err_format;
1866                         array_size -= sizeof(iv->data.d16);
1867
1868                         value = be16_to_cpu(iv->data.d16);
1869                         b43_write16(dev, offset, value);
1870
1871                         iv = (const struct b43_iv *)((const uint8_t *)iv +
1872                                                         sizeof(__be16) +
1873                                                         sizeof(__be16));
1874                 }
1875         }
1876         if (array_size)
1877                 goto err_format;
1878
1879         return 0;
1880
1881 err_format:
1882         b43err(dev->wl, "Initial Values Firmware file-format error.\n");
1883         b43_print_fw_helptext(dev->wl);
1884
1885         return -EPROTO;
1886 }
1887
1888 static int b43_upload_initvals(struct b43_wldev *dev)
1889 {
1890         const size_t hdr_len = sizeof(struct b43_fw_header);
1891         const struct b43_fw_header *hdr;
1892         struct b43_firmware *fw = &dev->fw;
1893         const struct b43_iv *ivals;
1894         size_t count;
1895         int err;
1896
1897         hdr = (const struct b43_fw_header *)(fw->initvals->data);
1898         ivals = (const struct b43_iv *)(fw->initvals->data + hdr_len);
1899         count = be32_to_cpu(hdr->size);
1900         err = b43_write_initvals(dev, ivals, count,
1901                                  fw->initvals->size - hdr_len);
1902         if (err)
1903                 goto out;
1904         if (fw->initvals_band) {
1905                 hdr = (const struct b43_fw_header *)(fw->initvals_band->data);
1906                 ivals = (const struct b43_iv *)(fw->initvals_band->data + hdr_len);
1907                 count = be32_to_cpu(hdr->size);
1908                 err = b43_write_initvals(dev, ivals, count,
1909                                          fw->initvals_band->size - hdr_len);
1910                 if (err)
1911                         goto out;
1912         }
1913 out:
1914
1915         return err;
1916 }
1917
1918 /* Initialize the GPIOs
1919  * http://bcm-specs.sipsolutions.net/GPIO
1920  */
1921 static int b43_gpio_init(struct b43_wldev *dev)
1922 {
1923         struct ssb_bus *bus = dev->dev->bus;
1924         struct ssb_device *gpiodev, *pcidev = NULL;
1925         u32 mask, set;
1926
1927         b43_write32(dev, B43_MMIO_MACCTL, b43_read32(dev, B43_MMIO_MACCTL)
1928                     & ~B43_MACCTL_GPOUTSMSK);
1929
1930         b43_leds_switch_all(dev, 0);
1931         b43_write16(dev, B43_MMIO_GPIO_MASK, b43_read16(dev, B43_MMIO_GPIO_MASK)
1932                     | 0x000F);
1933
1934         mask = 0x0000001F;
1935         set = 0x0000000F;
1936         if (dev->dev->bus->chip_id == 0x4301) {
1937                 mask |= 0x0060;
1938                 set |= 0x0060;
1939         }
1940         if (0 /* FIXME: conditional unknown */ ) {
1941                 b43_write16(dev, B43_MMIO_GPIO_MASK,
1942                             b43_read16(dev, B43_MMIO_GPIO_MASK)
1943                             | 0x0100);
1944                 mask |= 0x0180;
1945                 set |= 0x0180;
1946         }
1947         if (dev->dev->bus->sprom.r1.boardflags_lo & B43_BFL_PACTRL) {
1948                 b43_write16(dev, B43_MMIO_GPIO_MASK,
1949                             b43_read16(dev, B43_MMIO_GPIO_MASK)
1950                             | 0x0200);
1951                 mask |= 0x0200;
1952                 set |= 0x0200;
1953         }
1954         if (dev->dev->id.revision >= 2)
1955                 mask |= 0x0010; /* FIXME: This is redundant. */
1956
1957 #ifdef CONFIG_SSB_DRIVER_PCICORE
1958         pcidev = bus->pcicore.dev;
1959 #endif
1960         gpiodev = bus->chipco.dev ? : pcidev;
1961         if (!gpiodev)
1962                 return 0;
1963         ssb_write32(gpiodev, B43_GPIO_CONTROL,
1964                     (ssb_read32(gpiodev, B43_GPIO_CONTROL)
1965                      & mask) | set);
1966
1967         return 0;
1968 }
1969
1970 /* Turn off all GPIO stuff. Call this on module unload, for example. */
1971 static void b43_gpio_cleanup(struct b43_wldev *dev)
1972 {
1973         struct ssb_bus *bus = dev->dev->bus;
1974         struct ssb_device *gpiodev, *pcidev = NULL;
1975
1976 #ifdef CONFIG_SSB_DRIVER_PCICORE
1977         pcidev = bus->pcicore.dev;
1978 #endif
1979         gpiodev = bus->chipco.dev ? : pcidev;
1980         if (!gpiodev)
1981                 return;
1982         ssb_write32(gpiodev, B43_GPIO_CONTROL, 0);
1983 }
1984
1985 /* http://bcm-specs.sipsolutions.net/EnableMac */
1986 void b43_mac_enable(struct b43_wldev *dev)
1987 {
1988         dev->mac_suspended--;
1989         B43_WARN_ON(dev->mac_suspended < 0);
1990         if (dev->mac_suspended == 0) {
1991                 b43_write32(dev, B43_MMIO_MACCTL,
1992                             b43_read32(dev, B43_MMIO_MACCTL)
1993                             | B43_MACCTL_ENABLED);
1994                 b43_write32(dev, B43_MMIO_GEN_IRQ_REASON,
1995                             B43_IRQ_MAC_SUSPENDED);
1996                 /* Commit writes */
1997                 b43_read32(dev, B43_MMIO_MACCTL);
1998                 b43_read32(dev, B43_MMIO_GEN_IRQ_REASON);
1999                 b43_power_saving_ctl_bits(dev, 0);
2000         }
2001 }
2002
2003 /* http://bcm-specs.sipsolutions.net/SuspendMAC */
2004 void b43_mac_suspend(struct b43_wldev *dev)
2005 {
2006         int i;
2007         u32 tmp;
2008
2009         B43_WARN_ON(dev->mac_suspended < 0);
2010         if (dev->mac_suspended == 0) {
2011                 b43_power_saving_ctl_bits(dev, B43_PS_AWAKE);
2012                 b43_write32(dev, B43_MMIO_MACCTL,
2013                             b43_read32(dev, B43_MMIO_MACCTL)
2014                             & ~B43_MACCTL_ENABLED);
2015                 /* force pci to flush the write */
2016                 b43_read32(dev, B43_MMIO_MACCTL);
2017                 for (i = 10000; i; i--) {
2018                         tmp = b43_read32(dev, B43_MMIO_GEN_IRQ_REASON);
2019                         if (tmp & B43_IRQ_MAC_SUSPENDED)
2020                                 goto out;
2021                         udelay(1);
2022                 }
2023                 b43err(dev->wl, "MAC suspend failed\n");
2024         }
2025       out:
2026         dev->mac_suspended++;
2027 }
2028
2029 static void b43_adjust_opmode(struct b43_wldev *dev)
2030 {
2031         struct b43_wl *wl = dev->wl;
2032         u32 ctl;
2033         u16 cfp_pretbtt;
2034
2035         ctl = b43_read32(dev, B43_MMIO_MACCTL);
2036         /* Reset status to STA infrastructure mode. */
2037         ctl &= ~B43_MACCTL_AP;
2038         ctl &= ~B43_MACCTL_KEEP_CTL;
2039         ctl &= ~B43_MACCTL_KEEP_BADPLCP;
2040         ctl &= ~B43_MACCTL_KEEP_BAD;
2041         ctl &= ~B43_MACCTL_PROMISC;
2042         ctl &= ~B43_MACCTL_BEACPROMISC;
2043         ctl |= B43_MACCTL_INFRA;
2044
2045         if (b43_is_mode(wl, IEEE80211_IF_TYPE_AP))
2046                 ctl |= B43_MACCTL_AP;
2047         else if (b43_is_mode(wl, IEEE80211_IF_TYPE_IBSS))
2048                 ctl &= ~B43_MACCTL_INFRA;
2049
2050         if (wl->filter_flags & FIF_CONTROL)
2051                 ctl |= B43_MACCTL_KEEP_CTL;
2052         if (wl->filter_flags & FIF_FCSFAIL)
2053                 ctl |= B43_MACCTL_KEEP_BAD;
2054         if (wl->filter_flags & FIF_PLCPFAIL)
2055                 ctl |= B43_MACCTL_KEEP_BADPLCP;
2056         if (wl->filter_flags & FIF_PROMISC_IN_BSS)
2057                 ctl |= B43_MACCTL_PROMISC;
2058         if (wl->filter_flags & FIF_BCN_PRBRESP_PROMISC)
2059                 ctl |= B43_MACCTL_BEACPROMISC;
2060
2061         /* Workaround: On old hardware the HW-MAC-address-filter
2062          * doesn't work properly, so always run promisc in filter
2063          * it in software. */
2064         if (dev->dev->id.revision <= 4)
2065                 ctl |= B43_MACCTL_PROMISC;
2066
2067         b43_write32(dev, B43_MMIO_MACCTL, ctl);
2068
2069         cfp_pretbtt = 2;
2070         if ((ctl & B43_MACCTL_INFRA) && !(ctl & B43_MACCTL_AP)) {
2071                 if (dev->dev->bus->chip_id == 0x4306 &&
2072                     dev->dev->bus->chip_rev == 3)
2073                         cfp_pretbtt = 100;
2074                 else
2075                         cfp_pretbtt = 50;
2076         }
2077         b43_write16(dev, 0x612, cfp_pretbtt);
2078 }
2079
2080 static void b43_rate_memory_write(struct b43_wldev *dev, u16 rate, int is_ofdm)
2081 {
2082         u16 offset;
2083
2084         if (is_ofdm) {
2085                 offset = 0x480;
2086                 offset += (b43_plcp_get_ratecode_ofdm(rate) & 0x000F) * 2;
2087         } else {
2088                 offset = 0x4C0;
2089                 offset += (b43_plcp_get_ratecode_cck(rate) & 0x000F) * 2;
2090         }
2091         b43_shm_write16(dev, B43_SHM_SHARED, offset + 0x20,
2092                         b43_shm_read16(dev, B43_SHM_SHARED, offset));
2093 }
2094
2095 static void b43_rate_memory_init(struct b43_wldev *dev)
2096 {
2097         switch (dev->phy.type) {
2098         case B43_PHYTYPE_A:
2099         case B43_PHYTYPE_G:
2100                 b43_rate_memory_write(dev, B43_OFDM_RATE_6MB, 1);
2101                 b43_rate_memory_write(dev, B43_OFDM_RATE_12MB, 1);
2102                 b43_rate_memory_write(dev, B43_OFDM_RATE_18MB, 1);
2103                 b43_rate_memory_write(dev, B43_OFDM_RATE_24MB, 1);
2104                 b43_rate_memory_write(dev, B43_OFDM_RATE_36MB, 1);
2105                 b43_rate_memory_write(dev, B43_OFDM_RATE_48MB, 1);
2106                 b43_rate_memory_write(dev, B43_OFDM_RATE_54MB, 1);
2107                 if (dev->phy.type == B43_PHYTYPE_A)
2108                         break;
2109                 /* fallthrough */
2110         case B43_PHYTYPE_B:
2111                 b43_rate_memory_write(dev, B43_CCK_RATE_1MB, 0);
2112                 b43_rate_memory_write(dev, B43_CCK_RATE_2MB, 0);
2113                 b43_rate_memory_write(dev, B43_CCK_RATE_5MB, 0);
2114                 b43_rate_memory_write(dev, B43_CCK_RATE_11MB, 0);
2115                 break;
2116         default:
2117                 B43_WARN_ON(1);
2118         }
2119 }
2120
2121 /* Set the TX-Antenna for management frames sent by firmware. */
2122 static void b43_mgmtframe_txantenna(struct b43_wldev *dev, int antenna)
2123 {
2124         u16 ant = 0;
2125         u16 tmp;
2126
2127         switch (antenna) {
2128         case B43_ANTENNA0:
2129                 ant |= B43_TX4_PHY_ANT0;
2130                 break;
2131         case B43_ANTENNA1:
2132                 ant |= B43_TX4_PHY_ANT1;
2133                 break;
2134         case B43_ANTENNA_AUTO:
2135                 ant |= B43_TX4_PHY_ANTLAST;
2136                 break;
2137         default:
2138                 B43_WARN_ON(1);
2139         }
2140
2141         /* FIXME We also need to set the other flags of the PHY control field somewhere. */
2142
2143         /* For Beacons */
2144         tmp = b43_shm_read16(dev, B43_SHM_SHARED, B43_SHM_SH_BEACPHYCTL);
2145         tmp = (tmp & ~B43_TX4_PHY_ANT) | ant;
2146         b43_shm_write16(dev, B43_SHM_SHARED, B43_SHM_SH_BEACPHYCTL, tmp);
2147         /* For ACK/CTS */
2148         tmp = b43_shm_read16(dev, B43_SHM_SHARED, B43_SHM_SH_ACKCTSPHYCTL);
2149         tmp = (tmp & ~B43_TX4_PHY_ANT) | ant;
2150         b43_shm_write16(dev, B43_SHM_SHARED, B43_SHM_SH_ACKCTSPHYCTL, tmp);
2151         /* For Probe Resposes */
2152         tmp = b43_shm_read16(dev, B43_SHM_SHARED, B43_SHM_SH_PRPHYCTL);
2153         tmp = (tmp & ~B43_TX4_PHY_ANT) | ant;
2154         b43_shm_write16(dev, B43_SHM_SHARED, B43_SHM_SH_PRPHYCTL, tmp);
2155 }
2156
2157 /* Returns TRUE, if the radio is enabled in hardware. */
2158 static bool b43_is_hw_radio_enabled(struct b43_wldev *dev)
2159 {
2160         if (dev->phy.rev >= 3) {
2161                 if (!(b43_read32(dev, B43_MMIO_RADIO_HWENABLED_HI)
2162                       & B43_MMIO_RADIO_HWENABLED_HI_MASK))
2163                         return 1;
2164         } else {
2165                 if (b43_read16(dev, B43_MMIO_RADIO_HWENABLED_LO)
2166                     & B43_MMIO_RADIO_HWENABLED_LO_MASK)
2167                         return 1;
2168         }
2169         return 0;
2170 }
2171
2172 /* This is the opposite of b43_chip_init() */
2173 static void b43_chip_exit(struct b43_wldev *dev)
2174 {
2175         b43_radio_turn_off(dev);
2176         if (!modparam_noleds)
2177                 b43_leds_exit(dev);
2178         b43_gpio_cleanup(dev);
2179         /* firmware is released later */
2180 }
2181
2182 /* Initialize the chip
2183  * http://bcm-specs.sipsolutions.net/ChipInit
2184  */
2185 static int b43_chip_init(struct b43_wldev *dev)
2186 {
2187         struct b43_phy *phy = &dev->phy;
2188         int err, tmp;
2189         u32 value32;
2190         u16 value16;
2191
2192         b43_write32(dev, B43_MMIO_MACCTL,
2193                     B43_MACCTL_PSM_JMP0 | B43_MACCTL_IHR_ENABLED);
2194
2195         err = b43_request_firmware(dev);
2196         if (err)
2197                 goto out;
2198         err = b43_upload_microcode(dev);
2199         if (err)
2200                 goto out;       /* firmware is released later */
2201
2202         err = b43_gpio_init(dev);
2203         if (err)
2204                 goto out;       /* firmware is released later */
2205         err = b43_upload_initvals(dev);
2206         if (err)
2207                 goto err_gpio_cleanup;
2208         b43_radio_turn_on(dev);
2209
2210         b43_write16(dev, 0x03E6, 0x0000);
2211         err = b43_phy_init(dev);
2212         if (err)
2213                 goto err_radio_off;
2214
2215         /* Select initial Interference Mitigation. */
2216         tmp = phy->interfmode;
2217         phy->interfmode = B43_INTERFMODE_NONE;
2218         b43_radio_set_interference_mitigation(dev, tmp);
2219
2220         b43_set_rx_antenna(dev, B43_ANTENNA_DEFAULT);
2221         b43_mgmtframe_txantenna(dev, B43_ANTENNA_DEFAULT);
2222
2223         if (phy->type == B43_PHYTYPE_B) {
2224                 value16 = b43_read16(dev, 0x005E);
2225                 value16 |= 0x0004;
2226                 b43_write16(dev, 0x005E, value16);
2227         }
2228         b43_write32(dev, 0x0100, 0x01000000);
2229         if (dev->dev->id.revision < 5)
2230                 b43_write32(dev, 0x010C, 0x01000000);
2231
2232         b43_write32(dev, B43_MMIO_MACCTL, b43_read32(dev, B43_MMIO_MACCTL)
2233                     & ~B43_MACCTL_INFRA);
2234         b43_write32(dev, B43_MMIO_MACCTL, b43_read32(dev, B43_MMIO_MACCTL)
2235                     | B43_MACCTL_INFRA);
2236
2237         if (b43_using_pio(dev)) {
2238                 b43_write32(dev, 0x0210, 0x00000100);
2239                 b43_write32(dev, 0x0230, 0x00000100);
2240                 b43_write32(dev, 0x0250, 0x00000100);
2241                 b43_write32(dev, 0x0270, 0x00000100);
2242                 b43_shm_write16(dev, B43_SHM_SHARED, 0x0034, 0x0000);
2243         }
2244
2245         /* Probe Response Timeout value */
2246         /* FIXME: Default to 0, has to be set by ioctl probably... :-/ */
2247         b43_shm_write16(dev, B43_SHM_SHARED, 0x0074, 0x0000);
2248
2249         /* Initially set the wireless operation mode. */
2250         b43_adjust_opmode(dev);
2251
2252         if (dev->dev->id.revision < 3) {
2253                 b43_write16(dev, 0x060E, 0x0000);
2254                 b43_write16(dev, 0x0610, 0x8000);
2255                 b43_write16(dev, 0x0604, 0x0000);
2256                 b43_write16(dev, 0x0606, 0x0200);
2257         } else {
2258                 b43_write32(dev, 0x0188, 0x80000000);
2259                 b43_write32(dev, 0x018C, 0x02000000);
2260         }
2261         b43_write32(dev, B43_MMIO_GEN_IRQ_REASON, 0x00004000);
2262         b43_write32(dev, B43_MMIO_DMA0_IRQ_MASK, 0x0001DC00);
2263         b43_write32(dev, B43_MMIO_DMA1_IRQ_MASK, 0x0000DC00);
2264         b43_write32(dev, B43_MMIO_DMA2_IRQ_MASK, 0x0000DC00);
2265         b43_write32(dev, B43_MMIO_DMA3_IRQ_MASK, 0x0001DC00);
2266         b43_write32(dev, B43_MMIO_DMA4_IRQ_MASK, 0x0000DC00);
2267         b43_write32(dev, B43_MMIO_DMA5_IRQ_MASK, 0x0000DC00);
2268
2269         value32 = ssb_read32(dev->dev, SSB_TMSLOW);
2270         value32 |= 0x00100000;
2271         ssb_write32(dev->dev, SSB_TMSLOW, value32);
2272
2273         b43_write16(dev, B43_MMIO_POWERUP_DELAY,
2274                     dev->dev->bus->chipco.fast_pwrup_delay);
2275
2276         err = 0;
2277         b43dbg(dev->wl, "Chip initialized\n");
2278       out:
2279         return err;
2280
2281       err_radio_off:
2282         b43_radio_turn_off(dev);
2283       err_gpio_cleanup:
2284         b43_gpio_cleanup(dev);
2285         goto out;
2286 }
2287
2288 static void b43_periodic_every120sec(struct b43_wldev *dev)
2289 {
2290         struct b43_phy *phy = &dev->phy;
2291
2292         if (phy->type != B43_PHYTYPE_G || phy->rev < 2)
2293                 return;
2294
2295         b43_mac_suspend(dev);
2296         b43_lo_g_measure(dev);
2297         b43_mac_enable(dev);
2298         if (b43_has_hardware_pctl(phy))
2299                 b43_lo_g_ctl_mark_all_unused(dev);
2300 }
2301
2302 static void b43_periodic_every60sec(struct b43_wldev *dev)
2303 {
2304         struct b43_phy *phy = &dev->phy;
2305
2306         if (!b43_has_hardware_pctl(phy))
2307                 b43_lo_g_ctl_mark_all_unused(dev);
2308         if (dev->dev->bus->sprom.r1.boardflags_lo & B43_BFL_RSSI) {
2309                 b43_mac_suspend(dev);
2310                 b43_calc_nrssi_slope(dev);
2311                 if ((phy->radio_ver == 0x2050) && (phy->radio_rev == 8)) {
2312                         u8 old_chan = phy->channel;
2313
2314                         /* VCO Calibration */
2315                         if (old_chan >= 8)
2316                                 b43_radio_selectchannel(dev, 1, 0);
2317                         else
2318                                 b43_radio_selectchannel(dev, 13, 0);
2319                         b43_radio_selectchannel(dev, old_chan, 0);
2320                 }
2321                 b43_mac_enable(dev);
2322         }
2323 }
2324
2325 static void b43_periodic_every30sec(struct b43_wldev *dev)
2326 {
2327         /* Update device statistics. */
2328         b43_calculate_link_quality(dev);
2329 }
2330
2331 static void b43_periodic_every15sec(struct b43_wldev *dev)
2332 {
2333         struct b43_phy *phy = &dev->phy;
2334
2335         if (phy->type == B43_PHYTYPE_G) {
2336                 //TODO: update_aci_moving_average
2337                 if (phy->aci_enable && phy->aci_wlan_automatic) {
2338                         b43_mac_suspend(dev);
2339                         if (!phy->aci_enable && 1 /*TODO: not scanning? */ ) {
2340                                 if (0 /*TODO: bunch of conditions */ ) {
2341                                         b43_radio_set_interference_mitigation
2342                                             (dev, B43_INTERFMODE_MANUALWLAN);
2343                                 }
2344                         } else if (1 /*TODO*/) {
2345                                 /*
2346                                    if ((aci_average > 1000) && !(b43_radio_aci_scan(dev))) {
2347                                    b43_radio_set_interference_mitigation(dev,
2348                                    B43_INTERFMODE_NONE);
2349                                    }
2350                                  */
2351                         }
2352                         b43_mac_enable(dev);
2353                 } else if (phy->interfmode == B43_INTERFMODE_NONWLAN &&
2354                            phy->rev == 1) {
2355                         //TODO: implement rev1 workaround
2356                 }
2357         }
2358         b43_phy_xmitpower(dev); //FIXME: unless scanning?
2359         //TODO for APHY (temperature?)
2360 }
2361
2362 static void b43_periodic_every1sec(struct b43_wldev *dev)
2363 {
2364         bool radio_hw_enable;
2365
2366         /* check if radio hardware enabled status changed */
2367         radio_hw_enable = b43_is_hw_radio_enabled(dev);
2368         if (unlikely(dev->radio_hw_enable != radio_hw_enable)) {
2369                 dev->radio_hw_enable = radio_hw_enable;
2370                 b43info(dev->wl, "Radio hardware status changed to %s\n",
2371                         radio_hw_enable ? "ENABLED" : "DISABLED");
2372                 b43_leds_update(dev, 0);
2373         }
2374 }
2375
2376 static void do_periodic_work(struct b43_wldev *dev)
2377 {
2378         unsigned int state;
2379
2380         state = dev->periodic_state;
2381         if (state % 120 == 0)
2382                 b43_periodic_every120sec(dev);
2383         if (state % 60 == 0)
2384                 b43_periodic_every60sec(dev);
2385         if (state % 30 == 0)
2386                 b43_periodic_every30sec(dev);
2387         if (state % 15 == 0)
2388                 b43_periodic_every15sec(dev);
2389         b43_periodic_every1sec(dev);
2390 }
2391
2392 /* Estimate a "Badness" value based on the periodic work
2393  * state-machine state. "Badness" is worse (bigger), if the
2394  * periodic work will take longer.
2395  */
2396 static int estimate_periodic_work_badness(unsigned int state)
2397 {
2398         int badness = 0;
2399
2400         if (state % 120 == 0)   /* every 120 sec */
2401                 badness += 10;
2402         if (state % 60 == 0)    /* every 60 sec */
2403                 badness += 5;
2404         if (state % 30 == 0)    /* every 30 sec */
2405                 badness += 1;
2406         if (state % 15 == 0)    /* every 15 sec */
2407                 badness += 1;
2408
2409 #define BADNESS_LIMIT   4
2410         return badness;
2411 }
2412
2413 static void b43_periodic_work_handler(struct work_struct *work)
2414 {
2415         struct b43_wldev *dev =
2416             container_of(work, struct b43_wldev, periodic_work.work);
2417         unsigned long flags, delay;
2418         u32 savedirqs = 0;
2419         int badness;
2420
2421         mutex_lock(&dev->wl->mutex);
2422
2423         if (unlikely(b43_status(dev) != B43_STAT_STARTED))
2424                 goto out;
2425         if (b43_debug(dev, B43_DBG_PWORK_STOP))
2426                 goto out_requeue;
2427
2428         badness = estimate_periodic_work_badness(dev->periodic_state);
2429         if (badness > BADNESS_LIMIT) {
2430                 spin_lock_irqsave(&dev->wl->irq_lock, flags);
2431                 /* Suspend TX as we don't want to transmit packets while
2432                  * we recalibrate the hardware. */
2433                 b43_tx_suspend(dev);
2434                 savedirqs = b43_interrupt_disable(dev, B43_IRQ_ALL);
2435                 /* Periodic work will take a long time, so we want it to
2436                  * be preemtible and release the spinlock. */
2437                 spin_unlock_irqrestore(&dev->wl->irq_lock, flags);
2438                 b43_synchronize_irq(dev);
2439
2440                 do_periodic_work(dev);
2441
2442                 spin_lock_irqsave(&dev->wl->irq_lock, flags);
2443                 b43_interrupt_enable(dev, savedirqs);
2444                 b43_tx_resume(dev);
2445                 mmiowb();
2446                 spin_unlock_irqrestore(&dev->wl->irq_lock, flags);
2447         } else {
2448                 /* Take the global driver lock. This will lock any operation. */
2449                 spin_lock_irqsave(&dev->wl->irq_lock, flags);
2450
2451                 do_periodic_work(dev);
2452
2453                 mmiowb();
2454                 spin_unlock_irqrestore(&dev->wl->irq_lock, flags);
2455         }
2456         dev->periodic_state++;
2457       out_requeue:
2458         if (b43_debug(dev, B43_DBG_PWORK_FAST))
2459                 delay = msecs_to_jiffies(50);
2460         else
2461                 delay = round_jiffies(HZ);
2462         queue_delayed_work(dev->wl->hw->workqueue, &dev->periodic_work, delay);
2463       out:
2464         mutex_unlock(&dev->wl->mutex);
2465 }
2466
2467 static void b43_periodic_tasks_setup(struct b43_wldev *dev)
2468 {
2469         struct delayed_work *work = &dev->periodic_work;
2470
2471         dev->periodic_state = 0;
2472         INIT_DELAYED_WORK(work, b43_periodic_work_handler);
2473         queue_delayed_work(dev->wl->hw->workqueue, work, 0);
2474 }
2475
2476 /* Validate access to the chip (SHM) */
2477 static int b43_validate_chipaccess(struct b43_wldev *dev)
2478 {
2479         u32 value;
2480         u32 shm_backup;
2481
2482         shm_backup = b43_shm_read32(dev, B43_SHM_SHARED, 0);
2483         b43_shm_write32(dev, B43_SHM_SHARED, 0, 0xAA5555AA);
2484         if (b43_shm_read32(dev, B43_SHM_SHARED, 0) != 0xAA5555AA)
2485                 goto error;
2486         b43_shm_write32(dev, B43_SHM_SHARED, 0, 0x55AAAA55);
2487         if (b43_shm_read32(dev, B43_SHM_SHARED, 0) != 0x55AAAA55)
2488                 goto error;
2489         b43_shm_write32(dev, B43_SHM_SHARED, 0, shm_backup);
2490
2491         value = b43_read32(dev, B43_MMIO_MACCTL);
2492         if ((value | B43_MACCTL_GMODE) !=
2493             (B43_MACCTL_GMODE | B43_MACCTL_IHR_ENABLED))
2494                 goto error;
2495
2496         value = b43_read32(dev, B43_MMIO_GEN_IRQ_REASON);
2497         if (value)
2498                 goto error;
2499
2500         return 0;
2501       error:
2502         b43err(dev->wl, "Failed to validate the chipaccess\n");
2503         return -ENODEV;
2504 }
2505
2506 static void b43_security_init(struct b43_wldev *dev)
2507 {
2508         dev->max_nr_keys = (dev->dev->id.revision >= 5) ? 58 : 20;
2509         B43_WARN_ON(dev->max_nr_keys > ARRAY_SIZE(dev->key));
2510         dev->ktp = b43_shm_read16(dev, B43_SHM_SHARED, B43_SHM_SH_KTP);
2511         /* KTP is a word address, but we address SHM bytewise.
2512          * So multiply by two.
2513          */
2514         dev->ktp *= 2;
2515         if (dev->dev->id.revision >= 5) {
2516                 /* Number of RCMTA address slots */
2517                 b43_write16(dev, B43_MMIO_RCMTA_COUNT, dev->max_nr_keys - 8);
2518         }
2519         b43_clear_keys(dev);
2520 }
2521
2522 static int b43_rng_read(struct hwrng *rng, u32 * data)
2523 {
2524         struct b43_wl *wl = (struct b43_wl *)rng->priv;
2525         unsigned long flags;
2526
2527         /* Don't take wl->mutex here, as it could deadlock with
2528          * hwrng internal locking. It's not needed to take
2529          * wl->mutex here, anyway. */
2530
2531         spin_lock_irqsave(&wl->irq_lock, flags);
2532         *data = b43_read16(wl->current_dev, B43_MMIO_RNG);
2533         spin_unlock_irqrestore(&wl->irq_lock, flags);
2534
2535         return (sizeof(u16));
2536 }
2537
2538 static void b43_rng_exit(struct b43_wl *wl)
2539 {
2540         if (wl->rng_initialized)
2541                 hwrng_unregister(&wl->rng);
2542 }
2543
2544 static int b43_rng_init(struct b43_wl *wl)
2545 {
2546         int err;
2547
2548         snprintf(wl->rng_name, ARRAY_SIZE(wl->rng_name),
2549                  "%s_%s", KBUILD_MODNAME, wiphy_name(wl->hw->wiphy));
2550         wl->rng.name = wl->rng_name;
2551         wl->rng.data_read = b43_rng_read;
2552         wl->rng.priv = (unsigned long)wl;
2553         wl->rng_initialized = 1;
2554         err = hwrng_register(&wl->rng);
2555         if (err) {
2556                 wl->rng_initialized = 0;
2557                 b43err(wl, "Failed to register the random "
2558                        "number generator (%d)\n", err);
2559         }
2560
2561         return err;
2562 }
2563
2564 static int b43_tx(struct ieee80211_hw *hw,
2565                   struct sk_buff *skb, struct ieee80211_tx_control *ctl)
2566 {
2567         struct b43_wl *wl = hw_to_b43_wl(hw);
2568         struct b43_wldev *dev = wl->current_dev;
2569         int err = -ENODEV;
2570         unsigned long flags;
2571
2572         if (unlikely(!dev))
2573                 goto out;
2574         if (unlikely(b43_status(dev) < B43_STAT_STARTED))
2575                 goto out;
2576         /* DMA-TX is done without a global lock. */
2577         if (b43_using_pio(dev)) {
2578                 spin_lock_irqsave(&wl->irq_lock, flags);
2579                 err = b43_pio_tx(dev, skb, ctl);
2580                 spin_unlock_irqrestore(&wl->irq_lock, flags);
2581         } else
2582                 err = b43_dma_tx(dev, skb, ctl);
2583       out:
2584         if (unlikely(err))
2585                 return NETDEV_TX_BUSY;
2586         return NETDEV_TX_OK;
2587 }
2588
2589 static int b43_conf_tx(struct ieee80211_hw *hw,
2590                        int queue,
2591                        const struct ieee80211_tx_queue_params *params)
2592 {
2593         return 0;
2594 }
2595
2596 static int b43_get_tx_stats(struct ieee80211_hw *hw,
2597                             struct ieee80211_tx_queue_stats *stats)
2598 {
2599         struct b43_wl *wl = hw_to_b43_wl(hw);
2600         struct b43_wldev *dev = wl->current_dev;
2601         unsigned long flags;
2602         int err = -ENODEV;
2603
2604         if (!dev)
2605                 goto out;
2606         spin_lock_irqsave(&wl->irq_lock, flags);
2607         if (likely(b43_status(dev) >= B43_STAT_STARTED)) {
2608                 if (b43_using_pio(dev))
2609                         b43_pio_get_tx_stats(dev, stats);
2610                 else
2611                         b43_dma_get_tx_stats(dev, stats);
2612                 err = 0;
2613         }
2614         spin_unlock_irqrestore(&wl->irq_lock, flags);
2615       out:
2616         return err;
2617 }
2618
2619 static int b43_get_stats(struct ieee80211_hw *hw,
2620                          struct ieee80211_low_level_stats *stats)
2621 {
2622         struct b43_wl *wl = hw_to_b43_wl(hw);
2623         unsigned long flags;
2624
2625         spin_lock_irqsave(&wl->irq_lock, flags);
2626         memcpy(stats, &wl->ieee_stats, sizeof(*stats));
2627         spin_unlock_irqrestore(&wl->irq_lock, flags);
2628
2629         return 0;
2630 }
2631
2632 static const char *phymode_to_string(unsigned int phymode)
2633 {
2634         switch (phymode) {
2635         case B43_PHYMODE_A:
2636                 return "A";
2637         case B43_PHYMODE_B:
2638                 return "B";
2639         case B43_PHYMODE_G:
2640                 return "G";
2641         default:
2642                 B43_WARN_ON(1);
2643         }
2644         return "";
2645 }
2646
2647 static int find_wldev_for_phymode(struct b43_wl *wl,
2648                                   unsigned int phymode,
2649                                   struct b43_wldev **dev, bool * gmode)
2650 {
2651         struct b43_wldev *d;
2652
2653         list_for_each_entry(d, &wl->devlist, list) {
2654                 if (d->phy.possible_phymodes & phymode) {
2655                         /* Ok, this device supports the PHY-mode.
2656                          * Now figure out how the gmode bit has to be
2657                          * set to support it. */
2658                         if (phymode == B43_PHYMODE_A)
2659                                 *gmode = 0;
2660                         else
2661                                 *gmode = 1;
2662                         *dev = d;
2663
2664                         return 0;
2665                 }
2666         }
2667
2668         return -ESRCH;
2669 }
2670
2671 static void b43_put_phy_into_reset(struct b43_wldev *dev)
2672 {
2673         struct ssb_device *sdev = dev->dev;
2674         u32 tmslow;
2675
2676         tmslow = ssb_read32(sdev, SSB_TMSLOW);
2677         tmslow &= ~B43_TMSLOW_GMODE;
2678         tmslow |= B43_TMSLOW_PHYRESET;
2679         tmslow |= SSB_TMSLOW_FGC;
2680         ssb_write32(sdev, SSB_TMSLOW, tmslow);
2681         msleep(1);
2682
2683         tmslow = ssb_read32(sdev, SSB_TMSLOW);
2684         tmslow &= ~SSB_TMSLOW_FGC;
2685         tmslow |= B43_TMSLOW_PHYRESET;
2686         ssb_write32(sdev, SSB_TMSLOW, tmslow);
2687         msleep(1);
2688 }
2689
2690 /* Expects wl->mutex locked */
2691 static int b43_switch_phymode(struct b43_wl *wl, unsigned int new_mode)
2692 {
2693         struct b43_wldev *up_dev;
2694         struct b43_wldev *down_dev;
2695         int err;
2696         bool gmode = 0;
2697         int prev_status;
2698
2699         err = find_wldev_for_phymode(wl, new_mode, &up_dev, &gmode);
2700         if (err) {
2701                 b43err(wl, "Could not find a device for %s-PHY mode\n",
2702                        phymode_to_string(new_mode));
2703                 return err;
2704         }
2705         if ((up_dev == wl->current_dev) &&
2706             (!!wl->current_dev->phy.gmode == !!gmode)) {
2707                 /* This device is already running. */
2708                 return 0;
2709         }
2710         b43dbg(wl, "Reconfiguring PHYmode to %s-PHY\n",
2711                phymode_to_string(new_mode));
2712         down_dev = wl->current_dev;
2713
2714         prev_status = b43_status(down_dev);
2715         /* Shutdown the currently running core. */
2716         if (prev_status >= B43_STAT_STARTED)
2717                 b43_wireless_core_stop(down_dev);
2718         if (prev_status >= B43_STAT_INITIALIZED)
2719                 b43_wireless_core_exit(down_dev);
2720
2721         if (down_dev != up_dev) {
2722                 /* We switch to a different core, so we put PHY into
2723                  * RESET on the old core. */
2724                 b43_put_phy_into_reset(down_dev);
2725         }
2726
2727         /* Now start the new core. */
2728         up_dev->phy.gmode = gmode;
2729         if (prev_status >= B43_STAT_INITIALIZED) {
2730                 err = b43_wireless_core_init(up_dev);
2731                 if (err) {
2732                         b43err(wl, "Fatal: Could not initialize device for "
2733                                "newly selected %s-PHY mode\n",
2734                                phymode_to_string(new_mode));
2735                         goto init_failure;
2736                 }
2737         }
2738         if (prev_status >= B43_STAT_STARTED) {
2739                 err = b43_wireless_core_start(up_dev);
2740                 if (err) {
2741                         b43err(wl, "Fatal: Coult not start device for "
2742                                "newly selected %s-PHY mode\n",
2743                                phymode_to_string(new_mode));
2744                         b43_wireless_core_exit(up_dev);
2745                         goto init_failure;
2746                 }
2747         }
2748         B43_WARN_ON(b43_status(up_dev) != prev_status);
2749
2750         wl->current_dev = up_dev;
2751
2752         return 0;
2753       init_failure:
2754         /* Whoops, failed to init the new core. No core is operating now. */
2755         wl->current_dev = NULL;
2756         return err;
2757 }
2758
2759 static int b43_antenna_from_ieee80211(u8 antenna)
2760 {
2761         switch (antenna) {
2762         case 0:         /* default/diversity */
2763                 return B43_ANTENNA_DEFAULT;
2764         case 1:         /* Antenna 0 */
2765                 return B43_ANTENNA0;
2766         case 2:         /* Antenna 1 */
2767                 return B43_ANTENNA1;
2768         default:
2769                 return B43_ANTENNA_DEFAULT;
2770         }
2771 }
2772
2773 static int b43_dev_config(struct ieee80211_hw *hw, struct ieee80211_conf *conf)
2774 {
2775         struct b43_wl *wl = hw_to_b43_wl(hw);
2776         struct b43_wldev *dev;
2777         struct b43_phy *phy;
2778         unsigned long flags;
2779         unsigned int new_phymode = 0xFFFF;
2780         int antenna_tx;
2781         int antenna_rx;
2782         int err = 0;
2783         u32 savedirqs;
2784
2785         antenna_tx = b43_antenna_from_ieee80211(conf->antenna_sel_tx);
2786         antenna_rx = b43_antenna_from_ieee80211(conf->antenna_sel_rx);
2787
2788         mutex_lock(&wl->mutex);
2789
2790         /* Switch the PHY mode (if necessary). */
2791         switch (conf->phymode) {
2792         case MODE_IEEE80211A:
2793                 new_phymode = B43_PHYMODE_A;
2794                 break;
2795         case MODE_IEEE80211B:
2796                 new_phymode = B43_PHYMODE_B;
2797                 break;
2798         case MODE_IEEE80211G:
2799                 new_phymode = B43_PHYMODE_G;
2800                 break;
2801         default:
2802                 B43_WARN_ON(1);
2803         }
2804         err = b43_switch_phymode(wl, new_phymode);
2805         if (err)
2806                 goto out_unlock_mutex;
2807         dev = wl->current_dev;
2808         phy = &dev->phy;
2809
2810         /* Disable IRQs while reconfiguring the device.
2811          * This makes it possible to drop the spinlock throughout
2812          * the reconfiguration process. */
2813         spin_lock_irqsave(&wl->irq_lock, flags);
2814         if (b43_status(dev) < B43_STAT_STARTED) {
2815                 spin_unlock_irqrestore(&wl->irq_lock, flags);
2816                 goto out_unlock_mutex;
2817         }
2818         savedirqs = b43_interrupt_disable(dev, B43_IRQ_ALL);
2819         spin_unlock_irqrestore(&wl->irq_lock, flags);
2820         b43_synchronize_irq(dev);
2821
2822         /* Switch to the requested channel.
2823          * The firmware takes care of races with the TX handler. */
2824         if (conf->channel_val != phy->channel)
2825                 b43_radio_selectchannel(dev, conf->channel_val, 0);
2826
2827         /* Enable/Disable ShortSlot timing. */
2828         if ((!!(conf->flags & IEEE80211_CONF_SHORT_SLOT_TIME)) !=
2829             dev->short_slot) {
2830                 B43_WARN_ON(phy->type != B43_PHYTYPE_G);
2831                 if (conf->flags & IEEE80211_CONF_SHORT_SLOT_TIME)
2832                         b43_short_slot_timing_enable(dev);
2833                 else
2834                         b43_short_slot_timing_disable(dev);
2835         }
2836
2837         /* Adjust the desired TX power level. */
2838         if (conf->power_level != 0) {
2839                 if (conf->power_level != phy->power_level) {
2840                         phy->power_level = conf->power_level;
2841                         b43_phy_xmitpower(dev);
2842                 }
2843         }
2844
2845         /* Antennas for RX and management frame TX. */
2846         b43_mgmtframe_txantenna(dev, antenna_tx);
2847         b43_set_rx_antenna(dev, antenna_rx);
2848
2849         /* Update templates for AP mode. */
2850         if (b43_is_mode(wl, IEEE80211_IF_TYPE_AP))
2851                 b43_set_beacon_int(dev, conf->beacon_int);
2852
2853         if (!!conf->radio_enabled != phy->radio_on) {
2854                 if (conf->radio_enabled) {
2855                         b43_radio_turn_on(dev);
2856                         b43info(dev->wl, "Radio turned on by software\n");
2857                         if (!dev->radio_hw_enable) {
2858                                 b43info(dev->wl, "The hardware RF-kill button "
2859                                         "still turns the radio physically off. "
2860                                         "Press the button to turn it on.\n");
2861                         }
2862                 } else {
2863                         b43_radio_turn_off(dev);
2864                         b43info(dev->wl, "Radio turned off by software\n");
2865                 }
2866         }
2867
2868         spin_lock_irqsave(&wl->irq_lock, flags);
2869         b43_interrupt_enable(dev, savedirqs);
2870         mmiowb();
2871         spin_unlock_irqrestore(&wl->irq_lock, flags);
2872       out_unlock_mutex:
2873         mutex_unlock(&wl->mutex);
2874
2875         return err;
2876 }
2877
2878 static int b43_dev_set_key(struct ieee80211_hw *hw, enum set_key_cmd cmd,
2879                            const u8 *local_addr, const u8 *addr,
2880                            struct ieee80211_key_conf *key)
2881 {
2882         struct b43_wl *wl = hw_to_b43_wl(hw);
2883         struct b43_wldev *dev = wl->current_dev;
2884         unsigned long flags;
2885         u8 algorithm;
2886         u8 index;
2887         int err = -EINVAL;
2888         DECLARE_MAC_BUF(mac);
2889
2890         if (modparam_nohwcrypt)
2891                 return -ENOSPC; /* User disabled HW-crypto */
2892
2893         if (!dev)
2894                 return -ENODEV;
2895         switch (key->alg) {
2896         case ALG_NONE:
2897                 algorithm = B43_SEC_ALGO_NONE;
2898                 break;
2899         case ALG_WEP:
2900                 if (key->keylen == 5)
2901                         algorithm = B43_SEC_ALGO_WEP40;
2902                 else
2903                         algorithm = B43_SEC_ALGO_WEP104;
2904                 break;
2905         case ALG_TKIP:
2906                 algorithm = B43_SEC_ALGO_TKIP;
2907                 break;
2908         case ALG_CCMP:
2909                 algorithm = B43_SEC_ALGO_AES;
2910                 break;
2911         default:
2912                 B43_WARN_ON(1);
2913                 goto out;
2914         }
2915
2916         index = (u8) (key->keyidx);
2917         if (index > 3)
2918                 goto out;
2919
2920         mutex_lock(&wl->mutex);
2921         spin_lock_irqsave(&wl->irq_lock, flags);
2922
2923         if (b43_status(dev) < B43_STAT_INITIALIZED) {
2924                 err = -ENODEV;
2925                 goto out_unlock;
2926         }
2927
2928         switch (cmd) {
2929         case SET_KEY:
2930                 if (algorithm == B43_SEC_ALGO_TKIP) {
2931                         /* FIXME: No TKIP hardware encryption for now. */
2932                         err = -EOPNOTSUPP;
2933                         goto out_unlock;
2934                 }
2935
2936                 if (is_broadcast_ether_addr(addr)) {
2937                         /* addr is FF:FF:FF:FF:FF:FF for default keys */
2938                         err = b43_key_write(dev, index, algorithm,
2939                                             key->key, key->keylen, NULL, key);
2940                 } else {
2941                         /*
2942                          * either pairwise key or address is 00:00:00:00:00:00
2943                          * for transmit-only keys
2944                          */
2945                         err = b43_key_write(dev, -1, algorithm,
2946                                             key->key, key->keylen, addr, key);
2947                 }
2948                 if (err)
2949                         goto out_unlock;
2950
2951                 if (algorithm == B43_SEC_ALGO_WEP40 ||
2952                     algorithm == B43_SEC_ALGO_WEP104) {
2953                         b43_hf_write(dev, b43_hf_read(dev) | B43_HF_USEDEFKEYS);
2954                 } else {
2955                         b43_hf_write(dev,
2956                                      b43_hf_read(dev) & ~B43_HF_USEDEFKEYS);
2957                 }
2958                 key->flags |= IEEE80211_KEY_FLAG_GENERATE_IV;
2959                 break;
2960         case DISABLE_KEY: {
2961                 err = b43_key_clear(dev, key->hw_key_idx);
2962                 if (err)
2963                         goto out_unlock;
2964                 break;
2965         }
2966         default:
2967                 B43_WARN_ON(1);
2968         }
2969 out_unlock:
2970         spin_unlock_irqrestore(&wl->irq_lock, flags);
2971         mutex_unlock(&wl->mutex);
2972 out:
2973         if (!err) {
2974                 b43dbg(wl, "%s hardware based encryption for keyidx: %d, "
2975                        "mac: %s\n",
2976                        cmd == SET_KEY ? "Using" : "Disabling", key->keyidx,
2977                        print_mac(mac, addr));
2978         }
2979         return err;
2980 }
2981
2982 static void b43_configure_filter(struct ieee80211_hw *hw,
2983                                  unsigned int changed, unsigned int *fflags,
2984                                  int mc_count, struct dev_addr_list *mc_list)
2985 {
2986         struct b43_wl *wl = hw_to_b43_wl(hw);
2987         struct b43_wldev *dev = wl->current_dev;
2988         unsigned long flags;
2989
2990         if (!dev) {
2991                 *fflags = 0;
2992                 return;
2993         }
2994
2995         spin_lock_irqsave(&wl->irq_lock, flags);
2996         *fflags &= FIF_PROMISC_IN_BSS |
2997                   FIF_ALLMULTI |
2998                   FIF_FCSFAIL |
2999                   FIF_PLCPFAIL |
3000                   FIF_CONTROL |
3001                   FIF_OTHER_BSS |
3002                   FIF_BCN_PRBRESP_PROMISC;
3003
3004         changed &= FIF_PROMISC_IN_BSS |
3005                    FIF_ALLMULTI |
3006                    FIF_FCSFAIL |
3007                    FIF_PLCPFAIL |
3008                    FIF_CONTROL |
3009                    FIF_OTHER_BSS |
3010                    FIF_BCN_PRBRESP_PROMISC;
3011
3012         wl->filter_flags = *fflags;
3013
3014         if (changed && b43_status(dev) >= B43_STAT_INITIALIZED)
3015                 b43_adjust_opmode(dev);
3016         spin_unlock_irqrestore(&wl->irq_lock, flags);
3017 }
3018
3019 static int b43_config_interface(struct ieee80211_hw *hw,
3020                                 int if_id, struct ieee80211_if_conf *conf)
3021 {
3022         struct b43_wl *wl = hw_to_b43_wl(hw);
3023         struct b43_wldev *dev = wl->current_dev;
3024         unsigned long flags;
3025
3026         if (!dev)
3027                 return -ENODEV;
3028         mutex_lock(&wl->mutex);
3029         spin_lock_irqsave(&wl->irq_lock, flags);
3030         B43_WARN_ON(wl->if_id != if_id);
3031         if (conf->bssid)
3032                 memcpy(wl->bssid, conf->bssid, ETH_ALEN);
3033         else
3034                 memset(wl->bssid, 0, ETH_ALEN);
3035         if (b43_status(dev) >= B43_STAT_INITIALIZED) {
3036                 if (b43_is_mode(wl, IEEE80211_IF_TYPE_AP)) {
3037                         B43_WARN_ON(conf->type != IEEE80211_IF_TYPE_AP);
3038                         b43_set_ssid(dev, conf->ssid, conf->ssid_len);
3039                         if (conf->beacon)
3040                                 b43_refresh_templates(dev, conf->beacon);
3041                 }
3042                 b43_write_mac_bssid_templates(dev);
3043         }
3044         spin_unlock_irqrestore(&wl->irq_lock, flags);
3045         mutex_unlock(&wl->mutex);
3046
3047         return 0;
3048 }
3049
3050 /* Locking: wl->mutex */
3051 static void b43_wireless_core_stop(struct b43_wldev *dev)
3052 {
3053         struct b43_wl *wl = dev->wl;
3054         unsigned long flags;
3055
3056         if (b43_status(dev) < B43_STAT_STARTED)
3057                 return;
3058         b43_set_status(dev, B43_STAT_INITIALIZED);
3059
3060         mutex_unlock(&wl->mutex);
3061         /* Must unlock as it would otherwise deadlock. No races here.
3062          * Cancel the possibly running self-rearming periodic work. */
3063         cancel_delayed_work_sync(&dev->periodic_work);
3064         mutex_lock(&wl->mutex);
3065
3066         ieee80211_stop_queues(wl->hw);  //FIXME this could cause a deadlock, as mac80211 seems buggy.
3067
3068         /* Disable and sync interrupts. */
3069         spin_lock_irqsave(&wl->irq_lock, flags);
3070         dev->irq_savedstate = b43_interrupt_disable(dev, B43_IRQ_ALL);
3071         b43_read32(dev, B43_MMIO_GEN_IRQ_MASK); /* flush */
3072         spin_unlock_irqrestore(&wl->irq_lock, flags);
3073         b43_synchronize_irq(dev);
3074
3075         b43_mac_suspend(dev);
3076         free_irq(dev->dev->irq, dev);
3077         b43dbg(wl, "Wireless interface stopped\n");
3078 }
3079
3080 /* Locking: wl->mutex */
3081 static int b43_wireless_core_start(struct b43_wldev *dev)
3082 {
3083         int err;
3084
3085         B43_WARN_ON(b43_status(dev) != B43_STAT_INITIALIZED);
3086
3087         drain_txstatus_queue(dev);
3088         err = request_irq(dev->dev->irq, b43_interrupt_handler,
3089                           IRQF_SHARED, KBUILD_MODNAME, dev);
3090         if (err) {
3091                 b43err(dev->wl, "Cannot request IRQ-%d\n", dev->dev->irq);
3092                 goto out;
3093         }
3094
3095         /* We are ready to run. */
3096         b43_set_status(dev, B43_STAT_STARTED);
3097
3098         /* Start data flow (TX/RX). */
3099         b43_mac_enable(dev);
3100         b43_interrupt_enable(dev, dev->irq_savedstate);
3101         ieee80211_start_queues(dev->wl->hw);
3102
3103         /* Start maintainance work */
3104         b43_periodic_tasks_setup(dev);
3105
3106         b43dbg(dev->wl, "Wireless interface started\n");
3107       out:
3108         return err;
3109 }
3110
3111 /* Get PHY and RADIO versioning numbers */
3112 static int b43_phy_versioning(struct b43_wldev *dev)
3113 {
3114         struct b43_phy *phy = &dev->phy;
3115         u32 tmp;
3116         u8 analog_type;
3117         u8 phy_type;
3118         u8 phy_rev;
3119         u16 radio_manuf;
3120         u16 radio_ver;
3121         u16 radio_rev;
3122         int unsupported = 0;
3123
3124         /* Get PHY versioning */
3125         tmp = b43_read16(dev, B43_MMIO_PHY_VER);
3126         analog_type = (tmp & B43_PHYVER_ANALOG) >> B43_PHYVER_ANALOG_SHIFT;
3127         phy_type = (tmp & B43_PHYVER_TYPE) >> B43_PHYVER_TYPE_SHIFT;
3128         phy_rev = (tmp & B43_PHYVER_VERSION);
3129         switch (phy_type) {
3130         case B43_PHYTYPE_A:
3131                 if (phy_rev >= 4)
3132                         unsupported = 1;
3133                 break;
3134         case B43_PHYTYPE_B:
3135                 if (phy_rev != 2 && phy_rev != 4 && phy_rev != 6
3136                     && phy_rev != 7)
3137                         unsupported = 1;
3138                 break;
3139         case B43_PHYTYPE_G:
3140                 if (phy_rev > 8)
3141                         unsupported = 1;
3142                 break;
3143         default:
3144                 unsupported = 1;
3145         };
3146         if (unsupported) {
3147                 b43err(dev->wl, "FOUND UNSUPPORTED PHY "
3148                        "(Analog %u, Type %u, Revision %u)\n",
3149                        analog_type, phy_type, phy_rev);
3150                 return -EOPNOTSUPP;
3151         }
3152         b43dbg(dev->wl, "Found PHY: Analog %u, Type %u, Revision %u\n",
3153                analog_type, phy_type, phy_rev);
3154
3155         /* Get RADIO versioning */
3156         if (dev->dev->bus->chip_id == 0x4317) {
3157                 if (dev->dev->bus->chip_rev == 0)
3158                         tmp = 0x3205017F;
3159                 else if (dev->dev->bus->chip_rev == 1)
3160                         tmp = 0x4205017F;
3161                 else
3162                         tmp = 0x5205017F;
3163         } else {
3164                 b43_write16(dev, B43_MMIO_RADIO_CONTROL, B43_RADIOCTL_ID);
3165                 tmp = b43_read16(dev, B43_MMIO_RADIO_DATA_HIGH);
3166                 tmp <<= 16;
3167                 b43_write16(dev, B43_MMIO_RADIO_CONTROL, B43_RADIOCTL_ID);
3168                 tmp |= b43_read16(dev, B43_MMIO_RADIO_DATA_LOW);
3169         }
3170         radio_manuf = (tmp & 0x00000FFF);
3171         radio_ver = (tmp & 0x0FFFF000) >> 12;
3172         radio_rev = (tmp & 0xF0000000) >> 28;
3173         switch (phy_type) {
3174         case B43_PHYTYPE_A:
3175                 if (radio_ver != 0x2060)
3176                         unsupported = 1;
3177                 if (radio_rev != 1)
3178                         unsupported = 1;
3179                 if (radio_manuf != 0x17F)
3180                         unsupported = 1;
3181                 break;
3182         case B43_PHYTYPE_B:
3183                 if ((radio_ver & 0xFFF0) != 0x2050)
3184                         unsupported = 1;
3185                 break;
3186         case B43_PHYTYPE_G:
3187                 if (radio_ver != 0x2050)
3188                         unsupported = 1;
3189                 break;
3190         default:
3191                 B43_WARN_ON(1);
3192         }
3193         if (unsupported) {
3194                 b43err(dev->wl, "FOUND UNSUPPORTED RADIO "
3195                        "(Manuf 0x%X, Version 0x%X, Revision %u)\n",
3196                        radio_manuf, radio_ver, radio_rev);
3197                 return -EOPNOTSUPP;
3198         }
3199         b43dbg(dev->wl, "Found Radio: Manuf 0x%X, Version 0x%X, Revision %u\n",
3200                radio_manuf, radio_ver, radio_rev);
3201
3202         phy->radio_manuf = radio_manuf;
3203         phy->radio_ver = radio_ver;
3204         phy->radio_rev = radio_rev;
3205
3206         phy->analog = analog_type;
3207         phy->type = phy_type;
3208         phy->rev = phy_rev;
3209
3210         return 0;
3211 }
3212
3213 static void setup_struct_phy_for_init(struct b43_wldev *dev,
3214                                       struct b43_phy *phy)
3215 {
3216         struct b43_txpower_lo_control *lo;
3217         int i;
3218
3219         memset(phy->minlowsig, 0xFF, sizeof(phy->minlowsig));
3220         memset(phy->minlowsigpos, 0, sizeof(phy->minlowsigpos));
3221
3222         /* Flags */
3223         phy->locked = 0;
3224
3225         phy->aci_enable = 0;
3226         phy->aci_wlan_automatic = 0;
3227         phy->aci_hw_rssi = 0;
3228
3229         phy->radio_off_context.valid = 0;
3230
3231         lo = phy->lo_control;
3232         if (lo) {
3233                 memset(lo, 0, sizeof(*(phy->lo_control)));
3234                 lo->rebuild = 1;
3235                 lo->tx_bias = 0xFF;
3236         }
3237         phy->max_lb_gain = 0;
3238         phy->trsw_rx_gain = 0;
3239         phy->txpwr_offset = 0;
3240
3241         /* NRSSI */
3242         phy->nrssislope = 0;
3243         for (i = 0; i < ARRAY_SIZE(phy->nrssi); i++)
3244                 phy->nrssi[i] = -1000;
3245         for (i = 0; i < ARRAY_SIZE(phy->nrssi_lt); i++)
3246                 phy->nrssi_lt[i] = i;
3247
3248         phy->lofcal = 0xFFFF;
3249         phy->initval = 0xFFFF;
3250
3251         spin_lock_init(&phy->lock);
3252         phy->interfmode = B43_INTERFMODE_NONE;
3253         phy->channel = 0xFF;
3254
3255         phy->hardware_power_control = !!modparam_hwpctl;
3256 }
3257
3258 static void setup_struct_wldev_for_init(struct b43_wldev *dev)
3259 {
3260         /* Flags */
3261         dev->reg124_set_0x4 = 0;
3262         /* Assume the radio is enabled. If it's not enabled, the state will
3263          * immediately get fixed on the first periodic work run. */
3264         dev->radio_hw_enable = 1;
3265
3266         /* Stats */
3267         memset(&dev->stats, 0, sizeof(dev->stats));
3268
3269         setup_struct_phy_for_init(dev, &dev->phy);
3270
3271         /* IRQ related flags */
3272         dev->irq_reason = 0;
3273         memset(dev->dma_reason, 0, sizeof(dev->dma_reason));
3274         dev->irq_savedstate = B43_IRQ_MASKTEMPLATE;
3275
3276         dev->mac_suspended = 1;
3277
3278         /* Noise calculation context */
3279         memset(&dev->noisecalc, 0, sizeof(dev->noisecalc));
3280 }
3281
3282 static void b43_bluetooth_coext_enable(struct b43_wldev *dev)
3283 {
3284         struct ssb_sprom *sprom = &dev->dev->bus->sprom;
3285         u32 hf;
3286
3287         if (!(sprom->r1.boardflags_lo & B43_BFL_BTCOEXIST))
3288                 return;
3289         if (dev->phy.type != B43_PHYTYPE_B && !dev->phy.gmode)
3290                 return;
3291
3292         hf = b43_hf_read(dev);
3293         if (sprom->r1.boardflags_lo & B43_BFL_BTCMOD)
3294                 hf |= B43_HF_BTCOEXALT;
3295         else
3296                 hf |= B43_HF_BTCOEX;
3297         b43_hf_write(dev, hf);
3298         //TODO
3299 }
3300
3301 static void b43_bluetooth_coext_disable(struct b43_wldev *dev)
3302 {                               //TODO
3303 }
3304
3305 static void b43_imcfglo_timeouts_workaround(struct b43_wldev *dev)
3306 {
3307 #ifdef CONFIG_SSB_DRIVER_PCICORE
3308         struct ssb_bus *bus = dev->dev->bus;
3309         u32 tmp;
3310
3311         if (bus->pcicore.dev &&
3312             bus->pcicore.dev->id.coreid == SSB_DEV_PCI &&
3313             bus->pcicore.dev->id.revision <= 5) {
3314                 /* IMCFGLO timeouts workaround. */
3315                 tmp = ssb_read32(dev->dev, SSB_IMCFGLO);
3316                 tmp &= ~SSB_IMCFGLO_REQTO;
3317                 tmp &= ~SSB_IMCFGLO_SERTO;
3318                 switch (bus->bustype) {
3319                 case SSB_BUSTYPE_PCI:
3320                 case SSB_BUSTYPE_PCMCIA:
3321                         tmp |= 0x32;
3322                         break;
3323                 case SSB_BUSTYPE_SSB:
3324                         tmp |= 0x53;
3325                         break;
3326                 }
3327                 ssb_write32(dev->dev, SSB_IMCFGLO, tmp);
3328         }
3329 #endif /* CONFIG_SSB_DRIVER_PCICORE */
3330 }
3331
3332 /* Shutdown a wireless core */
3333 /* Locking: wl->mutex */
3334 static void b43_wireless_core_exit(struct b43_wldev *dev)
3335 {
3336         struct b43_phy *phy = &dev->phy;
3337
3338         B43_WARN_ON(b43_status(dev) > B43_STAT_INITIALIZED);
3339         if (b43_status(dev) != B43_STAT_INITIALIZED)
3340                 return;
3341         b43_set_status(dev, B43_STAT_UNINIT);
3342
3343         b43_rng_exit(dev->wl);
3344         b43_pio_free(dev);
3345         b43_dma_free(dev);
3346         b43_chip_exit(dev);
3347         b43_radio_turn_off(dev);
3348         b43_switch_analog(dev, 0);
3349         if (phy->dyn_tssi_tbl)
3350                 kfree(phy->tssi2dbm);
3351         kfree(phy->lo_control);
3352         phy->lo_control = NULL;
3353         ssb_device_disable(dev->dev, 0);
3354         ssb_bus_may_powerdown(dev->dev->bus);
3355 }
3356
3357 /* Initialize a wireless core */
3358 static int b43_wireless_core_init(struct b43_wldev *dev)
3359 {
3360         struct b43_wl *wl = dev->wl;
3361         struct ssb_bus *bus = dev->dev->bus;
3362         struct ssb_sprom *sprom = &bus->sprom;
3363         struct b43_phy *phy = &dev->phy;
3364         int err;
3365         u32 hf, tmp;
3366
3367         B43_WARN_ON(b43_status(dev) != B43_STAT_UNINIT);
3368
3369         err = ssb_bus_powerup(bus, 0);
3370         if (err)
3371                 goto out;
3372         if (!ssb_device_is_enabled(dev->dev)) {
3373                 tmp = phy->gmode ? B43_TMSLOW_GMODE : 0;
3374                 b43_wireless_core_reset(dev, tmp);
3375         }
3376
3377         if ((phy->type == B43_PHYTYPE_B) || (phy->type == B43_PHYTYPE_G)) {
3378                 phy->lo_control =
3379                     kzalloc(sizeof(*(phy->lo_control)), GFP_KERNEL);
3380                 if (!phy->lo_control) {
3381                         err = -ENOMEM;
3382                         goto err_busdown;
3383                 }
3384         }
3385         setup_struct_wldev_for_init(dev);
3386
3387         err = b43_phy_init_tssi2dbm_table(dev);
3388         if (err)
3389                 goto err_kfree_lo_control;
3390
3391         /* Enable IRQ routing to this device. */
3392         ssb_pcicore_dev_irqvecs_enable(&bus->pcicore, dev->dev);
3393
3394         b43_imcfglo_timeouts_workaround(dev);
3395         b43_bluetooth_coext_disable(dev);
3396         b43_phy_early_init(dev);
3397         err = b43_chip_init(dev);
3398         if (err)
3399                 goto err_kfree_tssitbl;
3400         b43_shm_write16(dev, B43_SHM_SHARED,
3401                         B43_SHM_SH_WLCOREREV, dev->dev->id.revision);
3402         hf = b43_hf_read(dev);
3403         if (phy->type == B43_PHYTYPE_G) {
3404                 hf |= B43_HF_SYMW;
3405                 if (phy->rev == 1)
3406                         hf |= B43_HF_GDCW;
3407                 if (sprom->r1.boardflags_lo & B43_BFL_PACTRL)
3408                         hf |= B43_HF_OFDMPABOOST;
3409         } else if (phy->type == B43_PHYTYPE_B) {
3410                 hf |= B43_HF_SYMW;
3411                 if (phy->rev >= 2 && phy->radio_ver == 0x2050)
3412                         hf &= ~B43_HF_GDCW;
3413         }
3414         b43_hf_write(dev, hf);
3415
3416         /* Short/Long Retry Limit.
3417          * The retry-limit is a 4-bit counter. Enforce this to avoid overflowing
3418          * the chip-internal counter.
3419          */
3420         tmp = limit_value(modparam_short_retry, 0, 0xF);
3421         b43_shm_write16(dev, B43_SHM_SCRATCH, B43_SHM_SC_SRLIMIT, tmp);
3422         tmp = limit_value(modparam_long_retry, 0, 0xF);
3423         b43_shm_write16(dev, B43_SHM_SCRATCH, B43_SHM_SC_LRLIMIT, tmp);
3424
3425         b43_shm_write16(dev, B43_SHM_SHARED, B43_SHM_SH_SFFBLIM, 3);
3426         b43_shm_write16(dev, B43_SHM_SHARED, B43_SHM_SH_LFFBLIM, 2);
3427
3428         /* Disable sending probe responses from firmware.
3429          * Setting the MaxTime to one usec will always trigger
3430          * a timeout, so we never send any probe resp.
3431          * A timeout of zero is infinite. */
3432         b43_shm_write16(dev, B43_SHM_SHARED, B43_SHM_SH_PRMAXTIME, 1);
3433
3434         b43_rate_memory_init(dev);
3435
3436         /* Minimum Contention Window */
3437         if (phy->type == B43_PHYTYPE_B) {
3438                 b43_shm_write16(dev, B43_SHM_SCRATCH, B43_SHM_SC_MINCONT, 0x1F);
3439         } else {
3440                 b43_shm_write16(dev, B43_SHM_SCRATCH, B43_SHM_SC_MINCONT, 0xF);
3441         }
3442         /* Maximum Contention Window */
3443         b43_shm_write16(dev, B43_SHM_SCRATCH, B43_SHM_SC_MAXCONT, 0x3FF);
3444
3445         do {
3446                 if (b43_using_pio(dev)) {
3447                         err = b43_pio_init(dev);
3448                 } else {
3449                         err = b43_dma_init(dev);
3450                         if (!err)
3451                                 b43_qos_init(dev);
3452                 }
3453         } while (err == -EAGAIN);
3454         if (err)
3455                 goto err_chip_exit;
3456
3457 //FIXME
3458 #if 1
3459         b43_write16(dev, 0x0612, 0x0050);
3460         b43_shm_write16(dev, B43_SHM_SHARED, 0x0416, 0x0050);
3461         b43_shm_write16(dev, B43_SHM_SHARED, 0x0414, 0x01F4);
3462 #endif
3463
3464         b43_bluetooth_coext_enable(dev);
3465
3466         ssb_bus_powerup(bus, 1);        /* Enable dynamic PCTL */
3467         memset(wl->bssid, 0, ETH_ALEN);
3468         memset(wl->mac_addr, 0, ETH_ALEN);
3469         b43_upload_card_macaddress(dev);
3470         b43_security_init(dev);
3471         b43_rng_init(wl);
3472
3473         b43_set_status(dev, B43_STAT_INITIALIZED);
3474
3475       out:
3476         return err;
3477
3478       err_chip_exit:
3479         b43_chip_exit(dev);
3480       err_kfree_tssitbl:
3481         if (phy->dyn_tssi_tbl)
3482                 kfree(phy->tssi2dbm);
3483       err_kfree_lo_control:
3484         kfree(phy->lo_control);
3485         phy->lo_control = NULL;
3486       err_busdown:
3487         ssb_bus_may_powerdown(bus);
3488         B43_WARN_ON(b43_status(dev) != B43_STAT_UNINIT);
3489         return err;
3490 }
3491
3492 static int b43_add_interface(struct ieee80211_hw *hw,
3493                              struct ieee80211_if_init_conf *conf)
3494 {
3495         struct b43_wl *wl = hw_to_b43_wl(hw);
3496         struct b43_wldev *dev;
3497         unsigned long flags;
3498         int err = -EOPNOTSUPP;
3499
3500         /* TODO: allow WDS/AP devices to coexist */
3501
3502         if (conf->type != IEEE80211_IF_TYPE_AP &&
3503             conf->type != IEEE80211_IF_TYPE_STA &&
3504             conf->type != IEEE80211_IF_TYPE_WDS &&
3505             conf->type != IEEE80211_IF_TYPE_IBSS)
3506                 return -EOPNOTSUPP;
3507
3508         mutex_lock(&wl->mutex);
3509         if (wl->operating)
3510                 goto out_mutex_unlock;
3511
3512         b43dbg(wl, "Adding Interface type %d\n", conf->type);
3513
3514         dev = wl->current_dev;
3515         wl->operating = 1;
3516         wl->if_id = conf->if_id;
3517         wl->if_type = conf->type;
3518         memcpy(wl->mac_addr, conf->mac_addr, ETH_ALEN);
3519
3520         spin_lock_irqsave(&wl->irq_lock, flags);
3521         b43_adjust_opmode(dev);
3522         b43_upload_card_macaddress(dev);
3523         spin_unlock_irqrestore(&wl->irq_lock, flags);
3524
3525         err = 0;
3526  out_mutex_unlock:
3527         mutex_unlock(&wl->mutex);
3528
3529         return err;
3530 }
3531
3532 static void b43_remove_interface(struct ieee80211_hw *hw,
3533                                  struct ieee80211_if_init_conf *conf)
3534 {
3535         struct b43_wl *wl = hw_to_b43_wl(hw);
3536         struct b43_wldev *dev = wl->current_dev;
3537         unsigned long flags;
3538
3539         b43dbg(wl, "Removing Interface type %d\n", conf->type);
3540
3541         mutex_lock(&wl->mutex);
3542
3543         B43_WARN_ON(!wl->operating);
3544         B43_WARN_ON(wl->if_id != conf->if_id);
3545
3546         wl->operating = 0;
3547
3548         spin_lock_irqsave(&wl->irq_lock, flags);
3549         b43_adjust_opmode(dev);
3550         memset(wl->mac_addr, 0, ETH_ALEN);
3551         b43_upload_card_macaddress(dev);
3552         spin_unlock_irqrestore(&wl->irq_lock, flags);
3553
3554         mutex_unlock(&wl->mutex);
3555 }
3556
3557 static int b43_start(struct ieee80211_hw *hw)
3558 {
3559         struct b43_wl *wl = hw_to_b43_wl(hw);
3560         struct b43_wldev *dev = wl->current_dev;
3561         int did_init = 0;
3562         int err;
3563
3564         mutex_lock(&wl->mutex);
3565
3566         if (b43_status(dev) < B43_STAT_INITIALIZED) {
3567                 err = b43_wireless_core_init(dev);
3568                 if (err)
3569                         goto out_mutex_unlock;
3570                 did_init = 1;
3571         }
3572
3573         if (b43_status(dev) < B43_STAT_STARTED) {
3574                 err = b43_wireless_core_start(dev);
3575                 if (err) {
3576                         if (did_init)
3577                                 b43_wireless_core_exit(dev);
3578                         goto out_mutex_unlock;
3579                 }
3580         }
3581
3582  out_mutex_unlock:
3583         mutex_unlock(&wl->mutex);
3584
3585         return err;
3586 }
3587
3588 void b43_stop(struct ieee80211_hw *hw)
3589 {
3590         struct b43_wl *wl = hw_to_b43_wl(hw);
3591         struct b43_wldev *dev = wl->current_dev;
3592
3593         mutex_lock(&wl->mutex);
3594         if (b43_status(dev) >= B43_STAT_STARTED)
3595                 b43_wireless_core_stop(dev);
3596         b43_wireless_core_exit(dev);
3597         mutex_unlock(&wl->mutex);
3598 }
3599
3600 static const struct ieee80211_ops b43_hw_ops = {
3601         .tx = b43_tx,
3602         .conf_tx = b43_conf_tx,
3603         .add_interface = b43_add_interface,
3604         .remove_interface = b43_remove_interface,
3605         .config = b43_dev_config,
3606         .config_interface = b43_config_interface,
3607         .configure_filter = b43_configure_filter,
3608         .set_key = b43_dev_set_key,
3609         .get_stats = b43_get_stats,
3610         .get_tx_stats = b43_get_tx_stats,
3611         .start = b43_start,
3612         .stop = b43_stop,
3613 };
3614
3615 /* Hard-reset the chip. Do not call this directly.
3616  * Use b43_controller_restart()
3617  */
3618 static void b43_chip_reset(struct work_struct *work)
3619 {
3620         struct b43_wldev *dev =
3621             container_of(work, struct b43_wldev, restart_work);
3622         struct b43_wl *wl = dev->wl;
3623         int err = 0;
3624         int prev_status;
3625
3626         mutex_lock(&wl->mutex);
3627
3628         prev_status = b43_status(dev);
3629         /* Bring the device down... */
3630         if (prev_status >= B43_STAT_STARTED)
3631                 b43_wireless_core_stop(dev);
3632         if (prev_status >= B43_STAT_INITIALIZED)
3633                 b43_wireless_core_exit(dev);
3634
3635         /* ...and up again. */
3636         if (prev_status >= B43_STAT_INITIALIZED) {
3637                 err = b43_wireless_core_init(dev);
3638                 if (err)
3639                         goto out;
3640         }
3641         if (prev_status >= B43_STAT_STARTED) {
3642                 err = b43_wireless_core_start(dev);
3643                 if (err) {
3644                         b43_wireless_core_exit(dev);
3645                         goto out;
3646                 }
3647         }
3648       out:
3649         mutex_unlock(&wl->mutex);
3650         if (err)
3651                 b43err(wl, "Controller restart FAILED\n");
3652         else
3653                 b43info(wl, "Controller restarted\n");
3654 }
3655
3656 static int b43_setup_modes(struct b43_wldev *dev,
3657                            int have_aphy, int have_bphy, int have_gphy)
3658 {
3659         struct ieee80211_hw *hw = dev->wl->hw;
3660         struct ieee80211_hw_mode *mode;
3661         struct b43_phy *phy = &dev->phy;
3662         int cnt = 0;
3663         int err;
3664
3665 /*FIXME: Don't tell ieee80211 about an A-PHY, because we currently don't support A-PHY. */
3666         have_aphy = 0;
3667
3668         phy->possible_phymodes = 0;
3669         for (; 1; cnt++) {
3670                 if (have_aphy) {
3671                         B43_WARN_ON(cnt >= B43_MAX_PHYHWMODES);
3672                         mode = &phy->hwmodes[cnt];
3673
3674                         mode->mode = MODE_IEEE80211A;
3675                         mode->num_channels = b43_a_chantable_size;
3676                         mode->channels = b43_a_chantable;
3677                         mode->num_rates = b43_a_ratetable_size;
3678                         mode->rates = b43_a_ratetable;
3679                         err = ieee80211_register_hwmode(hw, mode);
3680                         if (err)
3681                                 return err;
3682
3683                         phy->possible_phymodes |= B43_PHYMODE_A;
3684                         have_aphy = 0;
3685                         continue;
3686                 }
3687                 if (have_bphy) {
3688                         B43_WARN_ON(cnt >= B43_MAX_PHYHWMODES);
3689                         mode = &phy->hwmodes[cnt];
3690
3691                         mode->mode = MODE_IEEE80211B;
3692                         mode->num_channels = b43_bg_chantable_size;
3693                         mode->channels = b43_bg_chantable;
3694                         mode->num_rates = b43_b_ratetable_size;
3695                         mode->rates = b43_b_ratetable;
3696                         err = ieee80211_register_hwmode(hw, mode);
3697                         if (err)
3698                                 return err;
3699
3700                         phy->possible_phymodes |= B43_PHYMODE_B;
3701                         have_bphy = 0;
3702                         continue;
3703                 }
3704                 if (have_gphy) {
3705                         B43_WARN_ON(cnt >= B43_MAX_PHYHWMODES);
3706                         mode = &phy->hwmodes[cnt];
3707
3708                         mode->mode = MODE_IEEE80211G;
3709                         mode->num_channels = b43_bg_chantable_size;
3710                         mode->channels = b43_bg_chantable;
3711                         mode->num_rates = b43_g_ratetable_size;
3712                         mode->rates = b43_g_ratetable;
3713                         err = ieee80211_register_hwmode(hw, mode);
3714                         if (err)
3715                                 return err;
3716
3717                         phy->possible_phymodes |= B43_PHYMODE_G;
3718                         have_gphy = 0;
3719                         continue;
3720                 }
3721                 break;
3722         }
3723
3724         return 0;
3725 }
3726
3727 static void b43_wireless_core_detach(struct b43_wldev *dev)
3728 {
3729         /* We release firmware that late to not be required to re-request
3730          * is all the time when we reinit the core. */
3731         b43_release_firmware(dev);
3732 }
3733
3734 static int b43_wireless_core_attach(struct b43_wldev *dev)
3735 {
3736         struct b43_wl *wl = dev->wl;
3737         struct ssb_bus *bus = dev->dev->bus;
3738         struct pci_dev *pdev = bus->host_pci;
3739         int err;
3740         int have_aphy = 0, have_bphy = 0, have_gphy = 0;
3741         u32 tmp;
3742
3743         /* Do NOT do any device initialization here.
3744          * Do it in wireless_core_init() instead.
3745          * This function is for gathering basic information about the HW, only.
3746          * Also some structs may be set up here. But most likely you want to have
3747          * that in core_init(), too.
3748          */
3749
3750         err = ssb_bus_powerup(bus, 0);
3751         if (err) {
3752                 b43err(wl, "Bus powerup failed\n");
3753                 goto out;
3754         }
3755         /* Get the PHY type. */
3756         if (dev->dev->id.revision >= 5) {
3757                 u32 tmshigh;
3758
3759                 tmshigh = ssb_read32(dev->dev, SSB_TMSHIGH);
3760                 have_aphy = !!(tmshigh & B43_TMSHIGH_APHY);
3761                 have_gphy = !!(tmshigh & B43_TMSHIGH_GPHY);
3762                 if (!have_aphy && !have_gphy)
3763                         have_bphy = 1;
3764         } else if (dev->dev->id.revision == 4) {
3765                 have_gphy = 1;
3766                 have_aphy = 1;
3767         } else
3768                 have_bphy = 1;
3769
3770         /* Initialize LEDs structs. */
3771         err = b43_leds_init(dev);
3772         if (err)
3773                 goto err_powerdown;
3774
3775         dev->phy.gmode = (have_gphy || have_bphy);
3776         tmp = dev->phy.gmode ? B43_TMSLOW_GMODE : 0;
3777         b43_wireless_core_reset(dev, tmp);
3778
3779         err = b43_phy_versioning(dev);
3780         if (err)
3781                 goto err_leds_exit;
3782         /* Check if this device supports multiband. */
3783         if (!pdev ||
3784             (pdev->device != 0x4312 &&
3785              pdev->device != 0x4319 && pdev->device != 0x4324)) {
3786                 /* No multiband support. */
3787                 have_aphy = 0;
3788                 have_bphy = 0;
3789                 have_gphy = 0;
3790                 switch (dev->phy.type) {
3791                 case B43_PHYTYPE_A:
3792                         have_aphy = 1;
3793                         break;
3794                 case B43_PHYTYPE_B:
3795                         have_bphy = 1;
3796                         break;
3797                 case B43_PHYTYPE_G:
3798                         have_gphy = 1;
3799                         break;
3800                 default:
3801                         B43_WARN_ON(1);
3802                 }
3803         }
3804         dev->phy.gmode = (have_gphy || have_bphy);
3805         tmp = dev->phy.gmode ? B43_TMSLOW_GMODE : 0;
3806         b43_wireless_core_reset(dev, tmp);
3807
3808         err = b43_validate_chipaccess(dev);
3809         if (err)
3810                 goto err_leds_exit;
3811         err = b43_setup_modes(dev, have_aphy, have_bphy, have_gphy);
3812         if (err)
3813                 goto err_leds_exit;
3814
3815         /* Now set some default "current_dev" */
3816         if (!wl->current_dev)
3817                 wl->current_dev = dev;
3818         INIT_WORK(&dev->restart_work, b43_chip_reset);
3819
3820         b43_radio_turn_off(dev);
3821         b43_switch_analog(dev, 0);
3822         ssb_device_disable(dev->dev, 0);
3823         ssb_bus_may_powerdown(bus);
3824
3825 out:
3826         return err;
3827
3828 err_leds_exit:
3829         b43_leds_exit(dev);
3830 err_powerdown:
3831         ssb_bus_may_powerdown(bus);
3832         return err;
3833 }
3834
3835 static void b43_one_core_detach(struct ssb_device *dev)
3836 {
3837         struct b43_wldev *wldev;
3838         struct b43_wl *wl;
3839
3840         wldev = ssb_get_drvdata(dev);
3841         wl = wldev->wl;
3842         cancel_work_sync(&wldev->restart_work);
3843         b43_debugfs_remove_device(wldev);
3844         b43_wireless_core_detach(wldev);
3845         list_del(&wldev->list);
3846         wl->nr_devs--;
3847         ssb_set_drvdata(dev, NULL);
3848         kfree(wldev);
3849 }
3850
3851 static int b43_one_core_attach(struct ssb_device *dev, struct b43_wl *wl)
3852 {
3853         struct b43_wldev *wldev;
3854         struct pci_dev *pdev;
3855         int err = -ENOMEM;
3856
3857         if (!list_empty(&wl->devlist)) {
3858                 /* We are not the first core on this chip. */
3859                 pdev = dev->bus->host_pci;
3860                 /* Only special chips support more than one wireless
3861                  * core, although some of the other chips have more than
3862                  * one wireless core as well. Check for this and
3863                  * bail out early.
3864                  */
3865                 if (!pdev ||
3866                     ((pdev->device != 0x4321) &&
3867                      (pdev->device != 0x4313) && (pdev->device != 0x431A))) {
3868                         b43dbg(wl, "Ignoring unconnected 802.11 core\n");
3869                         return -ENODEV;
3870                 }
3871         }
3872
3873         wldev = kzalloc(sizeof(*wldev), GFP_KERNEL);
3874         if (!wldev)
3875                 goto out;
3876
3877         wldev->dev = dev;
3878         wldev->wl = wl;
3879         b43_set_status(wldev, B43_STAT_UNINIT);
3880         wldev->bad_frames_preempt = modparam_bad_frames_preempt;
3881         tasklet_init(&wldev->isr_tasklet,
3882                      (void (*)(unsigned long))b43_interrupt_tasklet,
3883                      (unsigned long)wldev);
3884         if (modparam_pio)
3885                 wldev->__using_pio = 1;
3886         INIT_LIST_HEAD(&wldev->list);
3887
3888         err = b43_wireless_core_attach(wldev);
3889         if (err)
3890                 goto err_kfree_wldev;
3891
3892         list_add(&wldev->list, &wl->devlist);
3893         wl->nr_devs++;
3894         ssb_set_drvdata(dev, wldev);
3895         b43_debugfs_add_device(wldev);
3896
3897       out:
3898         return err;
3899
3900       err_kfree_wldev:
3901         kfree(wldev);
3902         return err;
3903 }
3904
3905 static void b43_sprom_fixup(struct ssb_bus *bus)
3906 {
3907         /* boardflags workarounds */
3908         if (bus->boardinfo.vendor == SSB_BOARDVENDOR_DELL &&
3909             bus->chip_id == 0x4301 && bus->boardinfo.rev == 0x74)
3910                 bus->sprom.r1.boardflags_lo |= B43_BFL_BTCOEXIST;
3911         if (bus->boardinfo.vendor == PCI_VENDOR_ID_APPLE &&
3912             bus->boardinfo.type == 0x4E && bus->boardinfo.rev > 0x40)
3913                 bus->sprom.r1.boardflags_lo |= B43_BFL_PACTRL;
3914
3915         /* Handle case when gain is not set in sprom */
3916         if (bus->sprom.r1.antenna_gain_a == 0xFF)
3917                 bus->sprom.r1.antenna_gain_a = 2;
3918         if (bus->sprom.r1.antenna_gain_bg == 0xFF)
3919                 bus->sprom.r1.antenna_gain_bg = 2;
3920
3921         /* Convert Antennagain values to Q5.2 */
3922         bus->sprom.r1.antenna_gain_a <<= 2;
3923         bus->sprom.r1.antenna_gain_bg <<= 2;
3924 }
3925
3926 static void b43_wireless_exit(struct ssb_device *dev, struct b43_wl *wl)
3927 {
3928         struct ieee80211_hw *hw = wl->hw;
3929
3930         ssb_set_devtypedata(dev, NULL);
3931         ieee80211_free_hw(hw);
3932 }
3933
3934 static int b43_wireless_init(struct ssb_device *dev)
3935 {
3936         struct ssb_sprom *sprom = &dev->bus->sprom;
3937         struct ieee80211_hw *hw;
3938         struct b43_wl *wl;
3939         int err = -ENOMEM;
3940
3941         b43_sprom_fixup(dev->bus);
3942
3943         hw = ieee80211_alloc_hw(sizeof(*wl), &b43_hw_ops);
3944         if (!hw) {
3945                 b43err(NULL, "Could not allocate ieee80211 device\n");
3946                 goto out;
3947         }
3948
3949         /* fill hw info */
3950         hw->flags = IEEE80211_HW_HOST_GEN_BEACON_TEMPLATE;
3951         hw->max_signal = 100;
3952         hw->max_rssi = -110;
3953         hw->max_noise = -110;
3954         hw->queues = 1;         /* FIXME: hardware has more queues */
3955         SET_IEEE80211_DEV(hw, dev->dev);
3956         if (is_valid_ether_addr(sprom->r1.et1mac))
3957                 SET_IEEE80211_PERM_ADDR(hw, sprom->r1.et1mac);
3958         else
3959                 SET_IEEE80211_PERM_ADDR(hw, sprom->r1.il0mac);
3960
3961         /* Get and initialize struct b43_wl */
3962         wl = hw_to_b43_wl(hw);
3963         memset(wl, 0, sizeof(*wl));
3964         wl->hw = hw;
3965         spin_lock_init(&wl->irq_lock);
3966         spin_lock_init(&wl->leds_lock);
3967         mutex_init(&wl->mutex);
3968         INIT_LIST_HEAD(&wl->devlist);
3969
3970         ssb_set_devtypedata(dev, wl);
3971         b43info(wl, "Broadcom %04X WLAN found\n", dev->bus->chip_id);
3972         err = 0;
3973       out:
3974         return err;
3975 }
3976
3977 static int b43_probe(struct ssb_device *dev, const struct ssb_device_id *id)
3978 {
3979         struct b43_wl *wl;
3980         int err;
3981         int first = 0;
3982
3983         wl = ssb_get_devtypedata(dev);
3984         if (!wl) {
3985                 /* Probing the first core. Must setup common struct b43_wl */
3986                 first = 1;
3987                 err = b43_wireless_init(dev);
3988                 if (err)
3989                         goto out;
3990                 wl = ssb_get_devtypedata(dev);
3991                 B43_WARN_ON(!wl);
3992         }
3993         err = b43_one_core_attach(dev, wl);
3994         if (err)
3995                 goto err_wireless_exit;
3996
3997         if (first) {
3998                 err = ieee80211_register_hw(wl->hw);
3999                 if (err)
4000                         goto err_one_core_detach;
4001         }
4002
4003       out:
4004         return err;
4005
4006       err_one_core_detach:
4007         b43_one_core_detach(dev);
4008       err_wireless_exit:
4009         if (first)
4010                 b43_wireless_exit(dev, wl);
4011         return err;
4012 }
4013
4014 static void b43_remove(struct ssb_device *dev)
4015 {
4016         struct b43_wl *wl = ssb_get_devtypedata(dev);
4017         struct b43_wldev *wldev = ssb_get_drvdata(dev);
4018
4019         B43_WARN_ON(!wl);
4020         if (wl->current_dev == wldev)
4021                 ieee80211_unregister_hw(wl->hw);
4022
4023         b43_one_core_detach(dev);
4024
4025         if (list_empty(&wl->devlist)) {
4026                 /* Last core on the chip unregistered.
4027                  * We can destroy common struct b43_wl.
4028                  */
4029                 b43_wireless_exit(dev, wl);
4030         }
4031 }
4032
4033 /* Perform a hardware reset. This can be called from any context. */
4034 void b43_controller_restart(struct b43_wldev *dev, const char *reason)
4035 {
4036         /* Must avoid requeueing, if we are in shutdown. */
4037         if (b43_status(dev) < B43_STAT_INITIALIZED)
4038                 return;
4039         b43info(dev->wl, "Controller RESET (%s) ...\n", reason);
4040         queue_work(dev->wl->hw->workqueue, &dev->restart_work);
4041 }
4042
4043 #ifdef CONFIG_PM
4044
4045 static int b43_suspend(struct ssb_device *dev, pm_message_t state)
4046 {
4047         struct b43_wldev *wldev = ssb_get_drvdata(dev);
4048         struct b43_wl *wl = wldev->wl;
4049
4050         b43dbg(wl, "Suspending...\n");
4051
4052         mutex_lock(&wl->mutex);
4053         wldev->suspend_init_status = b43_status(wldev);
4054         if (wldev->suspend_init_status >= B43_STAT_STARTED)
4055                 b43_wireless_core_stop(wldev);
4056         if (wldev->suspend_init_status >= B43_STAT_INITIALIZED)
4057                 b43_wireless_core_exit(wldev);
4058         mutex_unlock(&wl->mutex);
4059
4060         b43dbg(wl, "Device suspended.\n");
4061
4062         return 0;
4063 }
4064
4065 static int b43_resume(struct ssb_device *dev)
4066 {
4067         struct b43_wldev *wldev = ssb_get_drvdata(dev);
4068         struct b43_wl *wl = wldev->wl;
4069         int err = 0;
4070
4071         b43dbg(wl, "Resuming...\n");
4072
4073         mutex_lock(&wl->mutex);
4074         if (wldev->suspend_init_status >= B43_STAT_INITIALIZED) {
4075                 err = b43_wireless_core_init(wldev);
4076                 if (err) {
4077                         b43err(wl, "Resume failed at core init\n");
4078                         goto out;
4079                 }
4080         }
4081         if (wldev->suspend_init_status >= B43_STAT_STARTED) {
4082                 err = b43_wireless_core_start(wldev);
4083                 if (err) {
4084                         b43_wireless_core_exit(wldev);
4085                         b43err(wl, "Resume failed at core start\n");
4086                         goto out;
4087                 }
4088         }
4089         mutex_unlock(&wl->mutex);
4090
4091         b43dbg(wl, "Device resumed.\n");
4092       out:
4093         return err;
4094 }
4095
4096 #else /* CONFIG_PM */
4097 # define b43_suspend    NULL
4098 # define b43_resume     NULL
4099 #endif /* CONFIG_PM */
4100
4101 static struct ssb_driver b43_ssb_driver = {
4102         .name           = KBUILD_MODNAME,
4103         .id_table       = b43_ssb_tbl,
4104         .probe          = b43_probe,
4105         .remove         = b43_remove,
4106         .suspend        = b43_suspend,
4107         .resume         = b43_resume,
4108 };
4109
4110 static int __init b43_init(void)
4111 {
4112         int err;
4113
4114         b43_debugfs_init();
4115         err = b43_pcmcia_init();
4116         if (err)
4117                 goto err_dfs_exit;
4118         err = ssb_driver_register(&b43_ssb_driver);
4119         if (err)
4120                 goto err_pcmcia_exit;
4121
4122         return err;
4123
4124 err_pcmcia_exit:
4125         b43_pcmcia_exit();
4126 err_dfs_exit:
4127         b43_debugfs_exit();
4128         return err;
4129 }
4130
4131 static void __exit b43_exit(void)
4132 {
4133         ssb_driver_unregister(&b43_ssb_driver);
4134         b43_pcmcia_exit();
4135         b43_debugfs_exit();
4136 }
4137
4138 module_init(b43_init)
4139 module_exit(b43_exit)