Merge branch 'for_linus' of git://git.kernel.org/pub/scm/linux/kernel/git/tytso/ext4
[sfrench/cifs-2.6.git] / drivers / staging / ath6kl / os / linux / ar6000_drv.c
1 //------------------------------------------------------------------------------
2 // Copyright (c) 2004-2010 Atheros Communications Inc.
3 // All rights reserved.
4 //
5 // 
6 //
7 // Permission to use, copy, modify, and/or distribute this software for any
8 // purpose with or without fee is hereby granted, provided that the above
9 // copyright notice and this permission notice appear in all copies.
10 //
11 // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12 // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13 // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14 // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15 // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16 // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17 // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18 //
19 //
20 //
21 // Author(s): ="Atheros"
22 //------------------------------------------------------------------------------
23
24 /*
25  * This driver is a pseudo ethernet driver to access the Atheros AR6000
26  * WLAN Device
27  */
28
29 #include "ar6000_drv.h"
30 #ifdef ATH6K_CONFIG_CFG80211
31 #include "cfg80211.h"
32 #endif /* ATH6K_CONFIG_CFG80211 */
33 #include "htc.h"
34 #include "wmi_filter_linux.h"
35 #include "epping_test.h"
36 #include "wlan_config.h"
37 #include "ar3kconfig.h"
38 #include "ar6k_pal.h"
39 #include "AR6002/addrs.h"
40
41
42 /* LINUX_HACK_FUDGE_FACTOR -- this is used to provide a workaround for linux behavior.  When
43  *  the meta data was added to the header it was found that linux did not correctly provide
44  *  enough headroom.  However when more headroom was requested beyond what was truly needed
45  *  Linux gave the requested headroom. Therefore to get the necessary headroom from Linux
46  *  the driver requests more than is needed by the amount = LINUX_HACK_FUDGE_FACTOR */
47 #define LINUX_HACK_FUDGE_FACTOR 16
48 #define BDATA_BDADDR_OFFSET     28
49
50 A_UINT8 bcast_mac[] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
51 A_UINT8 null_mac[] = {0x0, 0x0, 0x0, 0x0, 0x0, 0x0};
52
53 #ifdef DEBUG
54
55 #define  ATH_DEBUG_DBG_LOG       ATH_DEBUG_MAKE_MODULE_MASK(0)
56 #define  ATH_DEBUG_WLAN_CONNECT  ATH_DEBUG_MAKE_MODULE_MASK(1)
57 #define  ATH_DEBUG_WLAN_SCAN     ATH_DEBUG_MAKE_MODULE_MASK(2)
58 #define  ATH_DEBUG_WLAN_TX       ATH_DEBUG_MAKE_MODULE_MASK(3)
59 #define  ATH_DEBUG_WLAN_RX       ATH_DEBUG_MAKE_MODULE_MASK(4)
60 #define  ATH_DEBUG_HTC_RAW       ATH_DEBUG_MAKE_MODULE_MASK(5)
61 #define  ATH_DEBUG_HCI_BRIDGE    ATH_DEBUG_MAKE_MODULE_MASK(6)
62
63 static ATH_DEBUG_MASK_DESCRIPTION driver_debug_desc[] = {
64     { ATH_DEBUG_DBG_LOG      , "Target Debug Logs"},
65     { ATH_DEBUG_WLAN_CONNECT , "WLAN connect"},
66     { ATH_DEBUG_WLAN_SCAN    , "WLAN scan"},
67     { ATH_DEBUG_WLAN_TX      , "WLAN Tx"},
68     { ATH_DEBUG_WLAN_RX      , "WLAN Rx"},
69     { ATH_DEBUG_HTC_RAW      , "HTC Raw IF tracing"},
70     { ATH_DEBUG_HCI_BRIDGE   , "HCI Bridge Setup"},
71     { ATH_DEBUG_HCI_RECV     , "HCI Recv tracing"},
72     { ATH_DEBUG_HCI_DUMP     , "HCI Packet dumps"},
73 };
74
75 ATH_DEBUG_INSTANTIATE_MODULE_VAR(driver,
76                                  "driver",
77                                  "Linux Driver Interface",
78                                  ATH_DEBUG_MASK_DEFAULTS | ATH_DEBUG_WLAN_SCAN |
79                                  ATH_DEBUG_HCI_BRIDGE,
80                                  ATH_DEBUG_DESCRIPTION_COUNT(driver_debug_desc),
81                                  driver_debug_desc);
82
83 #endif
84
85
86 #define IS_MAC_NULL(mac) (mac[0]==0 && mac[1]==0 && mac[2]==0 && mac[3]==0 && mac[4]==0 && mac[5]==0)
87 #define IS_MAC_BCAST(mac) (*mac==0xff)
88
89 #define DESCRIPTION "Driver to access the Atheros AR600x Device, version " __stringify(__VER_MAJOR_) "." __stringify(__VER_MINOR_) "." __stringify(__VER_PATCH_) "." __stringify(__BUILD_NUMBER_)
90
91 MODULE_AUTHOR("Atheros Communications, Inc.");
92 MODULE_DESCRIPTION(DESCRIPTION);
93 MODULE_LICENSE("Dual BSD/GPL");
94
95 #ifndef REORG_APTC_HEURISTICS
96 #undef ADAPTIVE_POWER_THROUGHPUT_CONTROL
97 #endif /* REORG_APTC_HEURISTICS */
98
99 #ifdef ADAPTIVE_POWER_THROUGHPUT_CONTROL
100 #define APTC_TRAFFIC_SAMPLING_INTERVAL     100  /* msec */
101 #define APTC_UPPER_THROUGHPUT_THRESHOLD    3000 /* Kbps */
102 #define APTC_LOWER_THROUGHPUT_THRESHOLD    2000 /* Kbps */
103
104 typedef struct aptc_traffic_record {
105     A_BOOL timerScheduled;
106     struct timeval samplingTS;
107     unsigned long bytesReceived;
108     unsigned long bytesTransmitted;
109 } APTC_TRAFFIC_RECORD;
110
111 A_TIMER aptcTimer;
112 APTC_TRAFFIC_RECORD aptcTR;
113 #endif /* ADAPTIVE_POWER_THROUGHPUT_CONTROL */
114
115 #ifdef EXPORT_HCI_BRIDGE_INTERFACE
116 // callbacks registered by HCI transport driver
117 HCI_TRANSPORT_CALLBACKS ar6kHciTransCallbacks = { NULL };
118 #endif
119
120 unsigned int processDot11Hdr = 0;
121 int bmienable = BMIENABLE_DEFAULT;
122
123 char ifname[IFNAMSIZ] = {0,};
124
125 int wlaninitmode = WLAN_INIT_MODE_DEFAULT;
126 unsigned int bypasswmi = 0;
127 unsigned int debuglevel = 0;
128 int tspecCompliance = ATHEROS_COMPLIANCE;
129 unsigned int busspeedlow = 0;
130 unsigned int onebitmode = 0;
131 unsigned int skipflash = 0;
132 unsigned int wmitimeout = 2;
133 unsigned int wlanNodeCaching = 1;
134 unsigned int enableuartprint = ENABLEUARTPRINT_DEFAULT;
135 unsigned int logWmiRawMsgs = 0;
136 unsigned int enabletimerwar = 0;
137 unsigned int fwmode = 1;
138 unsigned int mbox_yield_limit = 99;
139 unsigned int enablerssicompensation = 0;
140 int reduce_credit_dribble = 1 + HTC_CONNECT_FLAGS_THRESHOLD_LEVEL_ONE_HALF;
141 int allow_trace_signal = 0;
142 #ifdef CONFIG_HOST_TCMD_SUPPORT
143 unsigned int testmode =0;
144 #endif
145
146 unsigned int irqprocmode = HIF_DEVICE_IRQ_SYNC_ONLY;//HIF_DEVICE_IRQ_ASYNC_SYNC;
147 unsigned int panic_on_assert = 1;
148 unsigned int nohifscattersupport = NOHIFSCATTERSUPPORT_DEFAULT;
149
150 unsigned int setuphci = SETUPHCI_DEFAULT;
151 unsigned int setuphcipal = SETUPHCIPAL_DEFAULT;
152 unsigned int loghci = 0;
153 unsigned int setupbtdev = SETUPBTDEV_DEFAULT;
154 #ifndef EXPORT_HCI_BRIDGE_INTERFACE
155 unsigned int ar3khcibaud = AR3KHCIBAUD_DEFAULT;
156 unsigned int hciuartscale = HCIUARTSCALE_DEFAULT;
157 unsigned int hciuartstep = HCIUARTSTEP_DEFAULT;
158 #endif
159 #ifdef CONFIG_CHECKSUM_OFFLOAD
160 unsigned int csumOffload=0;
161 unsigned int csumOffloadTest=0;
162 #endif
163 unsigned int eppingtest=0;
164
165 module_param_string(ifname, ifname, sizeof(ifname), 0644);
166 module_param(wlaninitmode, int, 0644);
167 module_param(bmienable, int, 0644);
168 module_param(bypasswmi, uint, 0644);
169 module_param(debuglevel, uint, 0644);
170 module_param(tspecCompliance, int, 0644);
171 module_param(onebitmode, uint, 0644);
172 module_param(busspeedlow, uint, 0644);
173 module_param(skipflash, uint, 0644);
174 module_param(wmitimeout, uint, 0644);
175 module_param(wlanNodeCaching, uint, 0644);
176 module_param(logWmiRawMsgs, uint, 0644);
177 module_param(enableuartprint, uint, 0644);
178 module_param(enabletimerwar, uint, 0644);
179 module_param(fwmode, uint, 0644);
180 module_param(mbox_yield_limit, uint, 0644);
181 module_param(reduce_credit_dribble, int, 0644);
182 module_param(allow_trace_signal, int, 0644);
183 module_param(enablerssicompensation, uint, 0644);
184 module_param(processDot11Hdr, uint, 0644);
185 #ifdef CONFIG_CHECKSUM_OFFLOAD
186 module_param(csumOffload, uint, 0644);
187 #endif
188 #ifdef CONFIG_HOST_TCMD_SUPPORT
189 module_param(testmode, uint, 0644);
190 #endif
191 module_param(irqprocmode, uint, 0644);
192 module_param(nohifscattersupport, uint, 0644);
193 module_param(panic_on_assert, uint, 0644);
194 module_param(setuphci, uint, 0644);
195 module_param(setuphcipal, uint, 0644);
196 module_param(loghci, uint, 0644);
197 module_param(setupbtdev, uint, 0644);
198 #ifndef EXPORT_HCI_BRIDGE_INTERFACE
199 module_param(ar3khcibaud, uint, 0644);
200 module_param(hciuartscale, uint, 0644);
201 module_param(hciuartstep, uint, 0644);
202 #endif
203 module_param(eppingtest, uint, 0644);
204
205 /* in 2.6.10 and later this is now a pointer to a uint */
206 unsigned int _mboxnum = HTC_MAILBOX_NUM_MAX;
207 #define mboxnum &_mboxnum
208
209 #ifdef DEBUG
210 A_UINT32 g_dbg_flags = DBG_DEFAULTS;
211 unsigned int debugflags = 0;
212 int debugdriver = 0;
213 unsigned int debughtc = 0;
214 unsigned int debugbmi = 0;
215 unsigned int debughif = 0;
216 unsigned int txcreditsavailable[HTC_MAILBOX_NUM_MAX] = {0};
217 unsigned int txcreditsconsumed[HTC_MAILBOX_NUM_MAX] = {0};
218 unsigned int txcreditintrenable[HTC_MAILBOX_NUM_MAX] = {0};
219 unsigned int txcreditintrenableaggregate[HTC_MAILBOX_NUM_MAX] = {0};
220 module_param(debugflags, uint, 0644);
221 module_param(debugdriver, int, 0644);
222 module_param(debughtc, uint, 0644);
223 module_param(debugbmi, uint, 0644);
224 module_param(debughif, uint, 0644);
225 module_param_array(txcreditsavailable, uint, mboxnum, 0644);
226 module_param_array(txcreditsconsumed, uint, mboxnum, 0644);
227 module_param_array(txcreditintrenable, uint, mboxnum, 0644);
228 module_param_array(txcreditintrenableaggregate, uint, mboxnum, 0644);
229
230 #endif /* DEBUG */
231
232 unsigned int resetok = 1;
233 unsigned int tx_attempt[HTC_MAILBOX_NUM_MAX] = {0};
234 unsigned int tx_post[HTC_MAILBOX_NUM_MAX] = {0};
235 unsigned int tx_complete[HTC_MAILBOX_NUM_MAX] = {0};
236 unsigned int hifBusRequestNumMax = 40;
237 unsigned int war23838_disabled = 0;
238 #ifdef ADAPTIVE_POWER_THROUGHPUT_CONTROL
239 unsigned int enableAPTCHeuristics = 1;
240 #endif /* ADAPTIVE_POWER_THROUGHPUT_CONTROL */
241 module_param_array(tx_attempt, uint, mboxnum, 0644);
242 module_param_array(tx_post, uint, mboxnum, 0644);
243 module_param_array(tx_complete, uint, mboxnum, 0644);
244 module_param(hifBusRequestNumMax, uint, 0644);
245 module_param(war23838_disabled, uint, 0644);
246 module_param(resetok, uint, 0644);
247 #ifdef ADAPTIVE_POWER_THROUGHPUT_CONTROL
248 module_param(enableAPTCHeuristics, uint, 0644);
249 #endif /* ADAPTIVE_POWER_THROUGHPUT_CONTROL */
250
251 #ifdef BLOCK_TX_PATH_FLAG
252 int blocktx = 0;
253 module_param(blocktx, int, 0644);
254 #endif /* BLOCK_TX_PATH_FLAG */
255
256 typedef struct user_rssi_compensation_t {
257     A_UINT16         customerID;
258     union {
259     A_UINT16         a_enable;
260     A_UINT16         bg_enable;
261     A_UINT16         enable;
262     };
263     A_INT16          bg_param_a;
264     A_INT16          bg_param_b;
265     A_INT16          a_param_a;
266     A_INT16          a_param_b;
267     A_UINT32         reserved;
268 } USER_RSSI_CPENSATION;
269
270 static USER_RSSI_CPENSATION rssi_compensation_param;
271
272 static A_INT16 rssi_compensation_table[96];
273
274 int reconnect_flag = 0;
275 static ar6k_pal_config_t ar6k_pal_config_g;
276
277 /* Function declarations */
278 static int ar6000_init_module(void);
279 static void ar6000_cleanup_module(void);
280
281 int ar6000_init(struct net_device *dev);
282 static int ar6000_open(struct net_device *dev);
283 static int ar6000_close(struct net_device *dev);
284 static void ar6000_init_control_info(AR_SOFTC_T *ar);
285 static int ar6000_data_tx(struct sk_buff *skb, struct net_device *dev);
286
287 void ar6000_destroy(struct net_device *dev, unsigned int unregister);
288 static void ar6000_detect_error(unsigned long ptr);
289 static void     ar6000_set_multicast_list(struct net_device *dev);
290 static struct net_device_stats *ar6000_get_stats(struct net_device *dev);
291 static struct iw_statistics *ar6000_get_iwstats(struct net_device * dev);
292
293 static void disconnect_timer_handler(unsigned long ptr);
294
295 void read_rssi_compensation_param(AR_SOFTC_T *ar);
296
297     /* for android builds we call external APIs that handle firmware download and configuration */
298 #ifdef ANDROID_ENV
299 /* !!!! Interim android support to make it easier to patch the default driver for
300  * android use. You must define an external source file ar6000_android.c that handles the following
301  * APIs */
302 extern void android_module_init(OSDRV_CALLBACKS *osdrvCallbacks);
303 extern void android_module_exit(void);
304 #endif
305 /*
306  * HTC service connection handlers
307  */
308 static A_STATUS ar6000_avail_ev(void *context, void *hif_handle);
309
310 static A_STATUS ar6000_unavail_ev(void *context, void *hif_handle);
311
312 A_STATUS ar6000_configure_target(AR_SOFTC_T *ar);
313
314 static void ar6000_target_failure(void *Instance, A_STATUS Status);
315
316 static void ar6000_rx(void *Context, HTC_PACKET *pPacket);
317
318 static void ar6000_rx_refill(void *Context,HTC_ENDPOINT_ID Endpoint);
319
320 static void ar6000_tx_complete(void *Context, HTC_PACKET_QUEUE *pPackets);
321
322 static HTC_SEND_FULL_ACTION ar6000_tx_queue_full(void *Context, HTC_PACKET *pPacket);
323
324 #ifdef ATH_AR6K_11N_SUPPORT
325 static void ar6000_alloc_netbufs(A_NETBUF_QUEUE_T *q, A_UINT16 num);
326 #endif
327 static void ar6000_deliver_frames_to_nw_stack(void * dev, void *osbuf);
328 //static void ar6000_deliver_frames_to_bt_stack(void * dev, void *osbuf);
329
330 static HTC_PACKET *ar6000_alloc_amsdu_rxbuf(void *Context, HTC_ENDPOINT_ID Endpoint, int Length);
331
332 static void ar6000_refill_amsdu_rxbufs(AR_SOFTC_T *ar, int Count);
333
334 static void ar6000_cleanup_amsdu_rxbufs(AR_SOFTC_T *ar);
335
336 static ssize_t
337 ar6000_sysfs_bmi_read(struct file *fp, struct kobject *kobj,
338                       struct bin_attribute *bin_attr,
339                       char *buf, loff_t pos, size_t count);
340
341 static ssize_t
342 ar6000_sysfs_bmi_write(struct file *fp, struct kobject *kobj,
343                        struct bin_attribute *bin_attr,
344                        char *buf, loff_t pos, size_t count);
345
346 static A_STATUS
347 ar6000_sysfs_bmi_init(AR_SOFTC_T *ar);
348
349 /* HCI PAL callback function declarations */
350 A_STATUS ar6k_setup_hci_pal(AR_SOFTC_T *ar);
351 void  ar6k_cleanup_hci_pal(AR_SOFTC_T *ar);
352
353 static void
354 ar6000_sysfs_bmi_deinit(AR_SOFTC_T *ar);
355
356 A_STATUS
357 ar6000_sysfs_bmi_get_config(AR_SOFTC_T *ar, A_UINT32 mode);
358
359 /*
360  * Static variables
361  */
362
363 struct net_device *ar6000_devices[MAX_AR6000];
364 static int is_netdev_registered;
365 extern struct iw_handler_def ath_iw_handler_def;
366 DECLARE_WAIT_QUEUE_HEAD(arEvent);
367 static void ar6000_cookie_init(AR_SOFTC_T *ar);
368 static void ar6000_cookie_cleanup(AR_SOFTC_T *ar);
369 static void ar6000_free_cookie(AR_SOFTC_T *ar, struct ar_cookie * cookie);
370 static struct ar_cookie *ar6000_alloc_cookie(AR_SOFTC_T *ar);
371
372 #ifdef USER_KEYS
373 static A_STATUS ar6000_reinstall_keys(AR_SOFTC_T *ar,A_UINT8 key_op_ctrl);
374 #endif
375
376 #ifdef CONFIG_AP_VIRTUAL_ADAPTER_SUPPORT
377 struct net_device *arApNetDev;
378 #endif /* CONFIG_AP_VIRTUAL_ADAPTER_SUPPORT */
379
380 static struct ar_cookie s_ar_cookie_mem[MAX_COOKIE_NUM];
381
382 #define HOST_INTEREST_ITEM_ADDRESS(ar, item) \
383         (((ar)->arTargetType == TARGET_TYPE_AR6002) ? AR6002_HOST_INTEREST_ITEM_ADDRESS(item) : \
384         (((ar)->arTargetType == TARGET_TYPE_AR6003) ? AR6003_HOST_INTEREST_ITEM_ADDRESS(item) : 0))
385
386
387 static struct net_device_ops ar6000_netdev_ops = {
388     .ndo_init               = NULL,
389     .ndo_open               = ar6000_open,
390     .ndo_stop               = ar6000_close,
391     .ndo_get_stats          = ar6000_get_stats,
392     .ndo_do_ioctl           = ar6000_ioctl,
393     .ndo_start_xmit         = ar6000_data_tx,
394     .ndo_set_multicast_list = ar6000_set_multicast_list,
395 };
396
397 /* Debug log support */
398
399 /*
400  * Flag to govern whether the debug logs should be parsed in the kernel
401  * or reported to the application.
402  */
403 #define REPORT_DEBUG_LOGS_TO_APP
404
405 A_STATUS
406 ar6000_set_host_app_area(AR_SOFTC_T *ar)
407 {
408     A_UINT32 address, data;
409     struct host_app_area_s host_app_area;
410
411     /* Fetch the address of the host_app_area_s instance in the host interest area */
412     address = TARG_VTOP(ar->arTargetType, HOST_INTEREST_ITEM_ADDRESS(ar, hi_app_host_interest));
413     if (ar6000_ReadRegDiag(ar->arHifDevice, &address, &data) != A_OK) {
414         return A_ERROR;
415     }
416     address = TARG_VTOP(ar->arTargetType, data);
417     host_app_area.wmi_protocol_ver = WMI_PROTOCOL_VERSION;
418     if (ar6000_WriteDataDiag(ar->arHifDevice, address,
419                              (A_UCHAR *)&host_app_area,
420                              sizeof(struct host_app_area_s)) != A_OK)
421     {
422         return A_ERROR;
423     }
424
425     return A_OK;
426 }
427
428 A_UINT32
429 dbglog_get_debug_hdr_ptr(AR_SOFTC_T *ar)
430 {
431     A_UINT32 param;
432     A_UINT32 address;
433     A_STATUS status;
434
435     address = TARG_VTOP(ar->arTargetType, HOST_INTEREST_ITEM_ADDRESS(ar, hi_dbglog_hdr));
436     if ((status = ar6000_ReadDataDiag(ar->arHifDevice, address,
437                                       (A_UCHAR *)&param, 4)) != A_OK)
438     {
439         param = 0;
440     }
441
442     return param;
443 }
444
445 /*
446  * The dbglog module has been initialized. Its ok to access the relevant
447  * data stuctures over the diagnostic window.
448  */
449 void
450 ar6000_dbglog_init_done(AR_SOFTC_T *ar)
451 {
452     ar->dbglog_init_done = TRUE;
453 }
454
455 A_UINT32
456 dbglog_get_debug_fragment(A_INT8 *datap, A_UINT32 len, A_UINT32 limit)
457 {
458     A_INT32 *buffer;
459     A_UINT32 count;
460     A_UINT32 numargs;
461     A_UINT32 length;
462     A_UINT32 fraglen;
463
464     count = fraglen = 0;
465     buffer = (A_INT32 *)datap;
466     length = (limit >> 2);
467
468     if (len <= limit) {
469         fraglen = len;
470     } else {
471         while (count < length) {
472             numargs = DBGLOG_GET_NUMARGS(buffer[count]);
473             fraglen = (count << 2);
474             count += numargs + 1;
475         }
476     }
477
478     return fraglen;
479 }
480
481 void
482 dbglog_parse_debug_logs(A_INT8 *datap, A_UINT32 len)
483 {
484     A_INT32 *buffer;
485     A_UINT32 count;
486     A_UINT32 timestamp;
487     A_UINT32 debugid;
488     A_UINT32 moduleid;
489     A_UINT32 numargs;
490     A_UINT32 length;
491
492     count = 0;
493     buffer = (A_INT32 *)datap;
494     length = (len >> 2);
495     while (count < length) {
496         debugid = DBGLOG_GET_DBGID(buffer[count]);
497         moduleid = DBGLOG_GET_MODULEID(buffer[count]);
498         numargs = DBGLOG_GET_NUMARGS(buffer[count]);
499         timestamp = DBGLOG_GET_TIMESTAMP(buffer[count]);
500         switch (numargs) {
501             case 0:
502             AR_DEBUG_PRINTF(ATH_DEBUG_DBG_LOG,("%d %d (%d)\n", moduleid, debugid, timestamp));
503             break;
504
505             case 1:
506             AR_DEBUG_PRINTF(ATH_DEBUG_DBG_LOG,("%d %d (%d): 0x%x\n", moduleid, debugid,
507                             timestamp, buffer[count+1]));
508             break;
509
510             case 2:
511             AR_DEBUG_PRINTF(ATH_DEBUG_DBG_LOG,("%d %d (%d): 0x%x, 0x%x\n", moduleid, debugid,
512                             timestamp, buffer[count+1], buffer[count+2]));
513             break;
514
515             default:
516             AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("Invalid args: %d\n", numargs));
517         }
518         count += numargs + 1;
519     }
520 }
521
522 int
523 ar6000_dbglog_get_debug_logs(AR_SOFTC_T *ar)
524 {
525     A_UINT32 data[8]; /* Should be able to accomodate struct dbglog_buf_s */
526     A_UINT32 address;
527     A_UINT32 length;
528     A_UINT32 dropped;
529     A_UINT32 firstbuf;
530     A_UINT32 debug_hdr_ptr;
531
532     if (!ar->dbglog_init_done) return A_ERROR;
533
534
535     AR6000_SPIN_LOCK(&ar->arLock, 0);
536
537     if (ar->dbgLogFetchInProgress) {
538         AR6000_SPIN_UNLOCK(&ar->arLock, 0);
539         return A_EBUSY;
540     }
541
542         /* block out others */
543     ar->dbgLogFetchInProgress = TRUE;
544
545     AR6000_SPIN_UNLOCK(&ar->arLock, 0);
546
547     debug_hdr_ptr = dbglog_get_debug_hdr_ptr(ar);
548     printk("debug_hdr_ptr: 0x%x\n", debug_hdr_ptr);
549
550     /* Get the contents of the ring buffer */
551     if (debug_hdr_ptr) {
552         address = TARG_VTOP(ar->arTargetType, debug_hdr_ptr);
553         length = 4 /* sizeof(dbuf) */ + 4 /* sizeof(dropped) */;
554         A_MEMZERO(data, sizeof(data));
555         ar6000_ReadDataDiag(ar->arHifDevice, address, (A_UCHAR *)data, length);
556         address = TARG_VTOP(ar->arTargetType, data[0] /* dbuf */);
557         firstbuf = address;
558         dropped = data[1]; /* dropped */
559         length = 4 /* sizeof(next) */ + 4 /* sizeof(buffer) */ + 4 /* sizeof(bufsize) */ + 4 /* sizeof(length) */ + 4 /* sizeof(count) */ + 4 /* sizeof(free) */;
560         A_MEMZERO(data, sizeof(data));
561         ar6000_ReadDataDiag(ar->arHifDevice, address, (A_UCHAR *)&data, length);
562
563         do {
564             address = TARG_VTOP(ar->arTargetType, data[1] /* buffer*/);
565             length = data[3]; /* length */
566             if ((length) && (length <= data[2] /* bufsize*/)) {
567                 /* Rewind the index if it is about to overrun the buffer */
568                 if (ar->log_cnt > (DBGLOG_HOST_LOG_BUFFER_SIZE - length)) {
569                     ar->log_cnt = 0;
570                 }
571                 if(A_OK != ar6000_ReadDataDiag(ar->arHifDevice, address,
572                                     (A_UCHAR *)&ar->log_buffer[ar->log_cnt], length))
573                 {
574                     break;
575                 }
576                 ar6000_dbglog_event(ar, dropped, (A_INT8*)&ar->log_buffer[ar->log_cnt], length);
577                 ar->log_cnt += length;
578             } else {
579                 AR_DEBUG_PRINTF(ATH_DEBUG_DBG_LOG,("Length: %d (Total size: %d)\n",
580                                 data[3], data[2]));
581             }
582
583             address = TARG_VTOP(ar->arTargetType, data[0] /* next */);
584             length = 4 /* sizeof(next) */ + 4 /* sizeof(buffer) */ + 4 /* sizeof(bufsize) */ + 4 /* sizeof(length) */ + 4 /* sizeof(count) */ + 4 /* sizeof(free) */;
585             A_MEMZERO(data, sizeof(data));
586             if(A_OK != ar6000_ReadDataDiag(ar->arHifDevice, address,
587                                 (A_UCHAR *)&data, length))
588             {
589                 break;
590             }
591
592         } while (address != firstbuf);
593     }
594
595     ar->dbgLogFetchInProgress = FALSE;
596
597     return A_OK;
598 }
599
600 void
601 ar6000_dbglog_event(AR_SOFTC_T *ar, A_UINT32 dropped,
602                     A_INT8 *buffer, A_UINT32 length)
603 {
604 #ifdef REPORT_DEBUG_LOGS_TO_APP
605     #define MAX_WIRELESS_EVENT_SIZE 252
606     /*
607      * Break it up into chunks of MAX_WIRELESS_EVENT_SIZE bytes of messages.
608      * There seems to be a limitation on the length of message that could be
609      * transmitted to the user app via this mechanism.
610      */
611     A_UINT32 send, sent;
612
613     sent = 0;
614     send = dbglog_get_debug_fragment(&buffer[sent], length - sent,
615                                      MAX_WIRELESS_EVENT_SIZE);
616     while (send) {
617         ar6000_send_event_to_app(ar, WMIX_DBGLOG_EVENTID, (A_UINT8*)&buffer[sent], send);
618         sent += send;
619         send = dbglog_get_debug_fragment(&buffer[sent], length - sent,
620                                          MAX_WIRELESS_EVENT_SIZE);
621     }
622 #else
623     AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("Dropped logs: 0x%x\nDebug info length: %d\n",
624                     dropped, length));
625
626     /* Interpret the debug logs */
627     dbglog_parse_debug_logs((A_INT8*)buffer, length);
628 #endif /* REPORT_DEBUG_LOGS_TO_APP */
629 }
630
631
632 static int __init
633 ar6000_init_module(void)
634 {
635     static int probed = 0;
636     A_STATUS status;
637     OSDRV_CALLBACKS osdrvCallbacks;
638
639     a_module_debug_support_init();
640
641 #ifdef DEBUG
642         /* check for debug mask overrides */
643     if (debughtc != 0) {
644         ATH_DEBUG_SET_DEBUG_MASK(htc,debughtc);
645     }
646     if (debugbmi != 0) {
647         ATH_DEBUG_SET_DEBUG_MASK(bmi,debugbmi);
648     }
649     if (debughif != 0) {
650         ATH_DEBUG_SET_DEBUG_MASK(hif,debughif);
651     }
652     if (debugdriver != 0) {
653         ATH_DEBUG_SET_DEBUG_MASK(driver,debugdriver);
654     }
655
656 #endif
657
658     A_REGISTER_MODULE_DEBUG_INFO(driver);
659
660     A_MEMZERO(&osdrvCallbacks,sizeof(osdrvCallbacks));
661     osdrvCallbacks.deviceInsertedHandler = ar6000_avail_ev;
662     osdrvCallbacks.deviceRemovedHandler = ar6000_unavail_ev;
663 #ifdef CONFIG_PM
664     osdrvCallbacks.deviceSuspendHandler = ar6000_suspend_ev;
665     osdrvCallbacks.deviceResumeHandler = ar6000_resume_ev;
666     osdrvCallbacks.devicePowerChangeHandler = ar6000_power_change_ev;
667 #endif
668
669     ar6000_pm_init();
670
671 #ifdef ANDROID_ENV
672     android_module_init(&osdrvCallbacks);
673 #endif
674
675 #ifdef DEBUG
676     /* Set the debug flags if specified at load time */
677     if(debugflags != 0)
678     {
679         g_dbg_flags = debugflags;
680     }
681 #endif
682
683     if (probed) {
684         return -ENODEV;
685     }
686     probed++;
687
688 #ifdef ADAPTIVE_POWER_THROUGHPUT_CONTROL
689     memset(&aptcTR, 0, sizeof(APTC_TRAFFIC_RECORD));
690 #endif /* ADAPTIVE_POWER_THROUGHPUT_CONTROL */
691
692 #ifdef CONFIG_HOST_GPIO_SUPPORT
693     ar6000_gpio_init();
694 #endif /* CONFIG_HOST_GPIO_SUPPORT */
695
696     status = HIFInit(&osdrvCallbacks);
697     if(status != A_OK)
698         return -ENODEV;
699
700     return 0;
701 }
702
703 static void __exit
704 ar6000_cleanup_module(void)
705 {
706     int i = 0;
707     struct net_device *ar6000_netdev;
708
709 #ifdef ADAPTIVE_POWER_THROUGHPUT_CONTROL
710     /* Delete the Adaptive Power Control timer */
711     if (timer_pending(&aptcTimer)) {
712         del_timer_sync(&aptcTimer);
713     }
714 #endif /* ADAPTIVE_POWER_THROUGHPUT_CONTROL */
715
716     for (i=0; i < MAX_AR6000; i++) {
717         if (ar6000_devices[i] != NULL) {
718             ar6000_netdev = ar6000_devices[i];
719             ar6000_devices[i] = NULL;
720             ar6000_destroy(ar6000_netdev, 1);
721         }
722     }
723
724     HIFShutDownDevice(NULL);
725
726     a_module_debug_support_cleanup();
727
728     ar6000_pm_exit();
729
730 #ifdef ANDROID_ENV    
731     android_module_exit();
732 #endif
733
734     AR_DEBUG_PRINTF(ATH_DEBUG_INFO,("ar6000_cleanup: success\n"));
735 }
736
737 #ifdef ADAPTIVE_POWER_THROUGHPUT_CONTROL
738 void
739 aptcTimerHandler(unsigned long arg)
740 {
741     A_UINT32 numbytes;
742     A_UINT32 throughput;
743     AR_SOFTC_T *ar;
744     A_STATUS status;
745
746     ar = (AR_SOFTC_T *)arg;
747     A_ASSERT(ar != NULL);
748     A_ASSERT(!timer_pending(&aptcTimer));
749
750     AR6000_SPIN_LOCK(&ar->arLock, 0);
751
752     /* Get the number of bytes transferred */
753     numbytes = aptcTR.bytesTransmitted + aptcTR.bytesReceived;
754     aptcTR.bytesTransmitted = aptcTR.bytesReceived = 0;
755
756     /* Calculate and decide based on throughput thresholds */
757     throughput = ((numbytes * 8)/APTC_TRAFFIC_SAMPLING_INTERVAL); /* Kbps */
758     if (throughput < APTC_LOWER_THROUGHPUT_THRESHOLD) {
759         /* Enable Sleep and delete the timer */
760         A_ASSERT(ar->arWmiReady == TRUE);
761         AR6000_SPIN_UNLOCK(&ar->arLock, 0);
762         status = wmi_powermode_cmd(ar->arWmi, REC_POWER);
763         AR6000_SPIN_LOCK(&ar->arLock, 0);
764         A_ASSERT(status == A_OK);
765         aptcTR.timerScheduled = FALSE;
766     } else {
767         A_TIMEOUT_MS(&aptcTimer, APTC_TRAFFIC_SAMPLING_INTERVAL, 0);
768     }
769
770     AR6000_SPIN_UNLOCK(&ar->arLock, 0);
771 }
772 #endif /* ADAPTIVE_POWER_THROUGHPUT_CONTROL */
773
774 #ifdef ATH_AR6K_11N_SUPPORT
775 static void
776 ar6000_alloc_netbufs(A_NETBUF_QUEUE_T *q, A_UINT16 num)
777 {
778     void * osbuf;
779
780     while(num) {
781         if((osbuf = A_NETBUF_ALLOC(AR6000_BUFFER_SIZE))) {
782             A_NETBUF_ENQUEUE(q, osbuf);
783         } else {
784             break;
785         }
786         num--;
787     }
788
789     if(num) {
790         A_PRINTF("%s(), allocation of netbuf failed", __func__);
791     }
792 }
793 #endif
794
795 static struct bin_attribute bmi_attr = {
796     .attr = {.name = "bmi", .mode = 0600},
797     .read = ar6000_sysfs_bmi_read,
798     .write = ar6000_sysfs_bmi_write,
799 };
800
801 static ssize_t
802 ar6000_sysfs_bmi_read(struct file *fp, struct kobject *kobj,
803                       struct bin_attribute *bin_attr,
804                       char *buf, loff_t pos, size_t count)
805 {
806     int index;
807     AR_SOFTC_T *ar;
808     HIF_DEVICE_OS_DEVICE_INFO   *osDevInfo;
809
810     AR_DEBUG_PRINTF(ATH_DEBUG_INFO,("BMI: Read %d bytes\n", (A_UINT32)count));
811     for (index=0; index < MAX_AR6000; index++) {
812         ar = (AR_SOFTC_T *)ar6k_priv(ar6000_devices[index]);
813         osDevInfo = &ar->osDevInfo;
814         if (kobj == (&(((struct device *)osDevInfo->pOSDevice)->kobj))) {
815             break;
816         }
817     }
818
819     if (index == MAX_AR6000) return 0;
820
821     if ((BMIRawRead(ar->arHifDevice, (A_UCHAR*)buf, count, TRUE)) != A_OK) {
822         return 0;
823     }
824
825     return count;
826 }
827
828 static ssize_t
829 ar6000_sysfs_bmi_write(struct file *fp, struct kobject *kobj,
830                        struct bin_attribute *bin_attr,
831                        char *buf, loff_t pos, size_t count)
832 {
833     int index;
834     AR_SOFTC_T *ar;
835     HIF_DEVICE_OS_DEVICE_INFO   *osDevInfo;
836
837     AR_DEBUG_PRINTF(ATH_DEBUG_INFO,("BMI: Write %d bytes\n", (A_UINT32)count));
838     for (index=0; index < MAX_AR6000; index++) {
839         ar = (AR_SOFTC_T *)ar6k_priv(ar6000_devices[index]);
840         osDevInfo = &ar->osDevInfo;
841         if (kobj == (&(((struct device *)osDevInfo->pOSDevice)->kobj))) {
842             break;
843         }
844     }
845
846     if (index == MAX_AR6000) return 0;
847
848     if ((BMIRawWrite(ar->arHifDevice, (A_UCHAR*)buf, count)) != A_OK) {
849         return 0;
850     }
851
852     return count;
853 }
854
855 static A_STATUS
856 ar6000_sysfs_bmi_init(AR_SOFTC_T *ar)
857 {
858     A_STATUS status;
859
860     AR_DEBUG_PRINTF(ATH_DEBUG_INFO,("BMI: Creating sysfs entry\n"));
861     A_MEMZERO(&ar->osDevInfo, sizeof(HIF_DEVICE_OS_DEVICE_INFO));
862
863     /* Get the underlying OS device */
864     status = HIFConfigureDevice(ar->arHifDevice,
865                                 HIF_DEVICE_GET_OS_DEVICE,
866                                 &ar->osDevInfo,
867                                 sizeof(HIF_DEVICE_OS_DEVICE_INFO));
868
869     if (A_FAILED(status)) {
870         AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("BMI: Failed to get OS device info from HIF\n"));
871         return A_ERROR;
872     }
873
874     /* Create a bmi entry in the sysfs filesystem */
875     if ((sysfs_create_bin_file(&(((struct device *)ar->osDevInfo.pOSDevice)->kobj), &bmi_attr)) < 0)
876     {
877         AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("BMI: Failed to create entry for bmi in sysfs filesystem\n"));
878         return A_ERROR;
879     }
880
881     return A_OK;
882 }
883
884 static void
885 ar6000_sysfs_bmi_deinit(AR_SOFTC_T *ar)
886 {
887     AR_DEBUG_PRINTF(ATH_DEBUG_INFO,("BMI: Deleting sysfs entry\n"));
888
889     sysfs_remove_bin_file(&(((struct device *)ar->osDevInfo.pOSDevice)->kobj), &bmi_attr);
890 }
891
892 #define bmifn(fn) do { \
893     if ((fn) < A_OK) { \
894         AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("BMI operation failed: %d\n", __LINE__)); \
895         return A_ERROR; \
896     } \
897 } while(0)
898
899 #ifdef INIT_MODE_DRV_ENABLED
900
901 #ifdef SOFTMAC_FILE_USED
902 #define AR6002_MAC_ADDRESS_OFFSET     0x0A
903 #define AR6003_MAC_ADDRESS_OFFSET     0x16
904 static
905 void calculate_crc(A_UINT32 TargetType, A_UCHAR *eeprom_data)
906 {
907     A_UINT16        *ptr_crc;
908     A_UINT16        *ptr16_eeprom;
909     A_UINT16        checksum;
910     A_UINT32        i;
911     A_UINT32        eeprom_size;
912
913     if (TargetType == TARGET_TYPE_AR6001)
914     {
915         eeprom_size = 512;
916         ptr_crc = (A_UINT16 *)eeprom_data;
917     }
918     else if (TargetType == TARGET_TYPE_AR6003)
919     {
920         eeprom_size = 1024;
921         ptr_crc = (A_UINT16 *)((A_UCHAR *)eeprom_data + 0x04);
922     }
923     else
924     {
925         eeprom_size = 768;
926         ptr_crc = (A_UINT16 *)((A_UCHAR *)eeprom_data + 0x04);
927     }
928
929
930     // Clear the crc
931     *ptr_crc = 0;
932
933     // Recalculate new CRC
934     checksum = 0;
935     ptr16_eeprom = (A_UINT16 *)eeprom_data;
936     for (i = 0;i < eeprom_size; i += 2)
937     {
938         checksum = checksum ^ (*ptr16_eeprom);
939         ptr16_eeprom++;
940     }
941     checksum = 0xFFFF ^ checksum;
942     *ptr_crc = checksum;
943 }
944
945 static void 
946 ar6000_softmac_update(AR_SOFTC_T *ar, A_UCHAR *eeprom_data, size_t size)
947 {
948     const char *source = "random generated";
949     const struct firmware *softmac_entry;
950     A_UCHAR *ptr_mac;
951     switch (ar->arTargetType) {
952     case TARGET_TYPE_AR6002:
953         ptr_mac = (A_UINT8 *)((A_UCHAR *)eeprom_data + AR6002_MAC_ADDRESS_OFFSET);
954         break;
955     case TARGET_TYPE_AR6003:
956         ptr_mac = (A_UINT8 *)((A_UCHAR *)eeprom_data + AR6003_MAC_ADDRESS_OFFSET);
957         break;
958     default:
959         AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("Invalid Target Type\n"));
960         return;
961     }
962         printk(KERN_DEBUG "MAC from EEPROM %pM\n", ptr_mac);
963
964     /* create a random MAC in case we cannot read file from system */
965     ptr_mac[0] = 0;
966     ptr_mac[1] = 0x03;
967     ptr_mac[2] = 0x7F;
968     ptr_mac[3] = random32() & 0xff; 
969     ptr_mac[4] = random32() & 0xff; 
970     ptr_mac[5] = random32() & 0xff; 
971     if ((A_REQUEST_FIRMWARE(&softmac_entry, "softmac", ((struct device *)ar->osDevInfo.pOSDevice))) == 0)
972     {
973         A_CHAR *macbuf = A_MALLOC_NOWAIT(softmac_entry->size+1);
974         if (macbuf) {            
975             unsigned int softmac[6];
976             memcpy(macbuf, softmac_entry->data, softmac_entry->size);
977             macbuf[softmac_entry->size] = '\0';
978             if (sscanf(macbuf, "%02x:%02x:%02x:%02x:%02x:%02x", 
979                         &softmac[0], &softmac[1], &softmac[2],
980                         &softmac[3], &softmac[4], &softmac[5])==6) {
981                 int i;
982                 for (i=0; i<6; ++i) {
983                     ptr_mac[i] = softmac[i] & 0xff;
984                 }
985                 source = "softmac file";
986             }
987             A_FREE(macbuf);
988         }
989         A_RELEASE_FIRMWARE(softmac_entry);
990     }
991         printk(KERN_DEBUG "MAC from %s %pM\n", source, ptr_mac);
992    calculate_crc(ar->arTargetType, eeprom_data);
993 }
994 #endif /* SOFTMAC_FILE_USED */
995
996 static A_STATUS
997 ar6000_transfer_bin_file(AR_SOFTC_T *ar, AR6K_BIN_FILE file, A_UINT32 address, A_BOOL compressed)
998 {
999     A_STATUS status;
1000     const char *filename;
1001     const struct firmware *fw_entry;
1002     A_UINT32 fw_entry_size;
1003
1004     switch (file) {
1005         case AR6K_OTP_FILE:
1006             if (ar->arVersion.target_ver == AR6003_REV1_VERSION) {
1007                 filename = AR6003_REV1_OTP_FILE;
1008             } else if (ar->arVersion.target_ver == AR6003_REV2_VERSION) {
1009                 filename = AR6003_REV2_OTP_FILE;
1010             } else {
1011                 AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("Unknown firmware revision: %d\n", ar->arVersion.target_ver));
1012                 return A_ERROR;
1013             }
1014             break;
1015
1016         case AR6K_FIRMWARE_FILE:
1017             if (ar->arVersion.target_ver == AR6003_REV1_VERSION) {
1018                 filename = AR6003_REV1_FIRMWARE_FILE;
1019             } else if (ar->arVersion.target_ver == AR6003_REV2_VERSION) {
1020                 filename = AR6003_REV2_FIRMWARE_FILE;
1021             } else {
1022                 AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("Unknown firmware revision: %d\n", ar->arVersion.target_ver));
1023                 return A_ERROR;
1024             }
1025             
1026             if (eppingtest) {
1027                 bypasswmi = TRUE;    
1028                 if (ar->arVersion.target_ver == AR6003_REV1_VERSION) {
1029                     filename = AR6003_REV1_EPPING_FIRMWARE_FILE;
1030                 } else if (ar->arVersion.target_ver == AR6003_REV2_VERSION) {
1031                     filename = AR6003_REV2_EPPING_FIRMWARE_FILE;
1032                 } else {
1033                     AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("eppingtest : unsupported firmware revision: %d\n", 
1034                         ar->arVersion.target_ver));
1035                     return A_ERROR;
1036                 }
1037                 compressed = 0;
1038             }
1039             
1040 #ifdef CONFIG_HOST_TCMD_SUPPORT
1041             if(testmode) {
1042                 if (ar->arVersion.target_ver == AR6003_REV1_VERSION) {
1043                     filename = AR6003_REV1_TCMD_FIRMWARE_FILE;
1044                 } else if (ar->arVersion.target_ver == AR6003_REV2_VERSION) {
1045                     filename = AR6003_REV2_TCMD_FIRMWARE_FILE;
1046                 } else {
1047                     AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("Unknown firmware revision: %d\n", ar->arVersion.target_ver));
1048                     return A_ERROR;
1049                 }
1050                 compressed = 0;
1051             }
1052 #endif 
1053 #ifdef HTC_RAW_INTERFACE
1054             if (!eppingtest && bypasswmi) {
1055                 if (ar->arVersion.target_ver == AR6003_REV1_VERSION) {
1056                     filename = AR6003_REV1_ART_FIRMWARE_FILE;
1057                 } else if (ar->arVersion.target_ver == AR6003_REV2_VERSION) {
1058                     filename = AR6003_REV2_ART_FIRMWARE_FILE;
1059                 } else {
1060                     AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("Unknown firmware revision: %d\n", ar->arVersion.target_ver));
1061                     return A_ERROR;
1062                 }
1063                 compressed = 0;                
1064             }
1065 #endif 
1066             break;
1067
1068         case AR6K_PATCH_FILE:
1069             if (ar->arVersion.target_ver == AR6003_REV1_VERSION) {
1070                 filename = AR6003_REV1_PATCH_FILE;
1071             } else if (ar->arVersion.target_ver == AR6003_REV2_VERSION) {
1072                 filename = AR6003_REV2_PATCH_FILE;
1073             } else {
1074                 AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("Unknown firmware revision: %d\n", ar->arVersion.target_ver));
1075                 return A_ERROR;
1076             }
1077             break;
1078
1079         case AR6K_BOARD_DATA_FILE:
1080             if (ar->arVersion.target_ver == AR6003_REV1_VERSION) {
1081                 filename = AR6003_REV1_BOARD_DATA_FILE;
1082             } else if (ar->arVersion.target_ver == AR6003_REV2_VERSION) {
1083                 filename = AR6003_REV2_BOARD_DATA_FILE;
1084             } else {
1085                 AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("Unknown firmware revision: %d\n", ar->arVersion.target_ver));
1086                 return A_ERROR;
1087             }
1088             break;
1089
1090         default:
1091             AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("Unknown file type: %d\n", file));
1092             return A_ERROR;
1093     }
1094     if ((A_REQUEST_FIRMWARE(&fw_entry, filename, ((struct device *)ar->osDevInfo.pOSDevice))) != 0)
1095     {
1096         AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("Failed to get %s\n", filename));
1097         return A_ENOENT;
1098     }
1099
1100 #ifdef SOFTMAC_FILE_USED
1101     if (file==AR6K_BOARD_DATA_FILE && fw_entry->data) {
1102         ar6000_softmac_update(ar, (A_UCHAR *)fw_entry->data, fw_entry->size);
1103     }
1104 #endif 
1105
1106
1107     fw_entry_size = fw_entry->size;
1108
1109     /* Load extended board data for AR6003 */
1110     if ((file==AR6K_BOARD_DATA_FILE) && (fw_entry->data)) {
1111         A_UINT32 board_ext_address;
1112         A_UINT32 board_ext_data_size;
1113         A_UINT32 board_data_size;
1114
1115         board_ext_data_size = (((ar)->arTargetType == TARGET_TYPE_AR6002) ? AR6002_BOARD_EXT_DATA_SZ : \
1116                                (((ar)->arTargetType == TARGET_TYPE_AR6003) ? AR6003_BOARD_EXT_DATA_SZ : 0));
1117
1118         board_data_size = (((ar)->arTargetType == TARGET_TYPE_AR6002) ? AR6002_BOARD_DATA_SZ : \
1119                           (((ar)->arTargetType == TARGET_TYPE_AR6003) ? AR6003_BOARD_DATA_SZ : 0));
1120         
1121         /* Determine where in Target RAM to write Board Data */
1122         bmifn(BMIReadMemory(ar->arHifDevice, HOST_INTEREST_ITEM_ADDRESS(ar, hi_board_ext_data), (A_UCHAR *)&board_ext_address, 4));
1123         AR_DEBUG_PRINTF(ATH_DEBUG_INFO, ("Board extended Data download address: 0x%x\n", board_ext_address));
1124
1125         /* check whether the target has allocated memory for extended board data and file contains extended board data */
1126         if ((board_ext_address) && (fw_entry->size == (board_data_size + board_ext_data_size))) {
1127             A_UINT32 param;
1128
1129             status = BMIWriteMemory(ar->arHifDevice, board_ext_address, (A_UCHAR *)(((A_UINT32)fw_entry->data) + board_data_size), board_ext_data_size);
1130
1131             if (status != A_OK) {
1132                 AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("BMI operation failed: %d\n", __LINE__));
1133                 A_RELEASE_FIRMWARE(fw_entry);
1134                 return A_ERROR;
1135             }
1136
1137             /* Record the fact that extended board Data IS initialized */
1138             param = 1;
1139             bmifn(BMIWriteMemory(ar->arHifDevice, HOST_INTEREST_ITEM_ADDRESS(ar, hi_board_ext_data_initialized), (A_UCHAR *)&param, 4));
1140         }
1141         fw_entry_size = board_data_size;
1142     }
1143
1144     if (compressed) {
1145         status = BMIFastDownload(ar->arHifDevice, address, (A_UCHAR *)fw_entry->data, fw_entry_size);
1146     } else {
1147         status = BMIWriteMemory(ar->arHifDevice, address, (A_UCHAR *)fw_entry->data, fw_entry_size);
1148     }
1149
1150     if (status != A_OK) {
1151         AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("BMI operation failed: %d\n", __LINE__));
1152         A_RELEASE_FIRMWARE(fw_entry);
1153         return A_ERROR;
1154     }
1155     A_RELEASE_FIRMWARE(fw_entry);
1156     return A_OK;
1157 }
1158 #endif /* INIT_MODE_DRV_ENABLED */
1159
1160 A_STATUS
1161 ar6000_update_bdaddr(AR_SOFTC_T *ar)
1162 {
1163
1164         if (setupbtdev != 0) {
1165             A_UINT32 address;
1166
1167            if (BMIReadMemory(ar->arHifDevice,
1168                 HOST_INTEREST_ITEM_ADDRESS(ar, hi_board_data), (A_UCHAR *)&address, 4) != A_OK)
1169            {
1170                 AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("BMIReadMemory for hi_board_data failed\n"));
1171                 return A_ERROR;
1172            }
1173
1174            if (BMIReadMemory(ar->arHifDevice, address + BDATA_BDADDR_OFFSET, (A_UCHAR *)ar->bdaddr, 6) != A_OK)
1175            {
1176                 AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("BMIReadMemory for BD address failed\n"));
1177                 return A_ERROR;
1178            }
1179            AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("BDADDR 0x%x:0x%x:0x%x:0x%x:0x%x:0x%x\n", ar->bdaddr[0],
1180                                                                 ar->bdaddr[1], ar->bdaddr[2], ar->bdaddr[3],
1181                                                                 ar->bdaddr[4], ar->bdaddr[5]));
1182         }
1183
1184 return A_OK;
1185 }
1186
1187 A_STATUS
1188 ar6000_sysfs_bmi_get_config(AR_SOFTC_T *ar, A_UINT32 mode)
1189 {
1190     AR_DEBUG_PRINTF(ATH_DEBUG_INFO,("BMI: Requesting device specific configuration\n"));
1191
1192     if (mode == WLAN_INIT_MODE_UDEV) {
1193         A_CHAR version[16];
1194         const struct firmware *fw_entry;
1195
1196         /* Get config using udev through a script in user space */
1197         sprintf(version, "%2.2x", ar->arVersion.target_ver);
1198         if ((A_REQUEST_FIRMWARE(&fw_entry, version, ((struct device *)ar->osDevInfo.pOSDevice))) != 0)
1199         {
1200             AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("BMI: Failure to get configuration for target version: %s\n", version));
1201             return A_ERROR;
1202         }
1203
1204         A_RELEASE_FIRMWARE(fw_entry);
1205 #ifdef INIT_MODE_DRV_ENABLED
1206     } else {
1207         /* The config is contained within the driver itself */
1208         A_STATUS status;
1209         A_UINT32 param, options, sleep, address;
1210
1211         /* Temporarily disable system sleep */
1212         address = MBOX_BASE_ADDRESS + LOCAL_SCRATCH_ADDRESS;
1213         bmifn(BMIReadSOCRegister(ar->arHifDevice, address, &param));
1214         options = param;
1215         param |= AR6K_OPTION_SLEEP_DISABLE;
1216         bmifn(BMIWriteSOCRegister(ar->arHifDevice, address, param));
1217
1218         address = RTC_BASE_ADDRESS + SYSTEM_SLEEP_ADDRESS;
1219         bmifn(BMIReadSOCRegister(ar->arHifDevice, address, &param));
1220         sleep = param;
1221         param |= WLAN_SYSTEM_SLEEP_DISABLE_SET(1);
1222         bmifn(BMIWriteSOCRegister(ar->arHifDevice, address, param));
1223         AR_DEBUG_PRINTF(ATH_DEBUG_INFO, ("old options: %d, old sleep: %d\n", options, sleep));
1224
1225         if (ar->arTargetType == TARGET_TYPE_AR6003) {
1226             /* Program analog PLL register */
1227             bmifn(BMIWriteSOCRegister(ar->arHifDevice, ANALOG_INTF_BASE_ADDRESS + 0x284, 0xF9104001));
1228             /* Run at 80/88MHz by default */
1229             param = CPU_CLOCK_STANDARD_SET(1);
1230         } else {
1231             /* Run at 40/44MHz by default */
1232             param = CPU_CLOCK_STANDARD_SET(0);
1233         }
1234         address = RTC_BASE_ADDRESS + CPU_CLOCK_ADDRESS;
1235         bmifn(BMIWriteSOCRegister(ar->arHifDevice, address, param));
1236
1237         param = 0;
1238         if (ar->arTargetType == TARGET_TYPE_AR6002) {
1239             bmifn(BMIReadMemory(ar->arHifDevice, HOST_INTEREST_ITEM_ADDRESS(ar, hi_ext_clk_detected), (A_UCHAR *)&param, 4));
1240         }
1241
1242         /* LPO_CAL.ENABLE = 1 if no external clk is detected */
1243         if (param != 1) {
1244             address = RTC_BASE_ADDRESS + LPO_CAL_ADDRESS;
1245             param = LPO_CAL_ENABLE_SET(1);
1246             bmifn(BMIWriteSOCRegister(ar->arHifDevice, address, param));
1247         }
1248
1249         /* Venus2.0: Lower SDIO pad drive strength,
1250          * temporary WAR to avoid SDIO CRC error */
1251         if (ar->arVersion.target_ver == AR6003_REV2_VERSION) {
1252             AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("AR6K: Temporary WAR to avoid SDIO CRC error\n"));
1253             param = 0x20;
1254             address = GPIO_BASE_ADDRESS + GPIO_PIN10_ADDRESS;
1255             bmifn(BMIWriteSOCRegister(ar->arHifDevice, address, param));
1256
1257             address = GPIO_BASE_ADDRESS + GPIO_PIN11_ADDRESS;
1258             bmifn(BMIWriteSOCRegister(ar->arHifDevice, address, param));
1259
1260             address = GPIO_BASE_ADDRESS + GPIO_PIN12_ADDRESS;
1261             bmifn(BMIWriteSOCRegister(ar->arHifDevice, address, param));
1262
1263             address = GPIO_BASE_ADDRESS + GPIO_PIN13_ADDRESS;
1264             bmifn(BMIWriteSOCRegister(ar->arHifDevice, address, param));
1265         }
1266
1267 #ifdef FORCE_INTERNAL_CLOCK
1268         /* Ignore external clock, if any, and force use of internal clock */
1269         if (ar->arTargetType == TARGET_TYPE_AR6003) {
1270             /* hi_ext_clk_detected = 0 */
1271             param = 0;
1272             bmifn(BMIWriteMemory(ar->arHifDevice, HOST_INTEREST_ITEM_ADDRESS(ar, hi_ext_clk_detected), (A_UCHAR *)&param, 4));
1273
1274             /* CLOCK_CONTROL &= ~LF_CLK32 */
1275             address = RTC_BASE_ADDRESS + CLOCK_CONTROL_ADDRESS;
1276             bmifn(BMIReadSOCRegister(ar->arHifDevice, address, &param));
1277             param &= (~CLOCK_CONTROL_LF_CLK32_SET(1));
1278             bmifn(BMIWriteSOCRegister(ar->arHifDevice, address, param));
1279         }
1280 #endif /* FORCE_INTERNAL_CLOCK */
1281
1282         /* Transfer Board Data from Target EEPROM to Target RAM */
1283         if (ar->arTargetType == TARGET_TYPE_AR6003) {
1284             /* Determine where in Target RAM to write Board Data */
1285             bmifn(BMIReadMemory(ar->arHifDevice, HOST_INTEREST_ITEM_ADDRESS(ar, hi_board_data), (A_UCHAR *)&address, 4));
1286             AR_DEBUG_PRINTF(ATH_DEBUG_INFO, ("Board Data download address: 0x%x\n", address));
1287
1288             /* Write EEPROM data to Target RAM */
1289             if ((ar6000_transfer_bin_file(ar, AR6K_BOARD_DATA_FILE, address, FALSE)) != A_OK) {
1290                 return A_ERROR;
1291             }
1292
1293             /* Record the fact that Board Data IS initialized */
1294             param = 1;
1295             bmifn(BMIWriteMemory(ar->arHifDevice, HOST_INTEREST_ITEM_ADDRESS(ar, hi_board_data_initialized), (A_UCHAR *)&param, 4));
1296
1297             /* Transfer One time Programmable data */
1298             AR6K_DATA_DOWNLOAD_ADDRESS(address, ar->arVersion.target_ver);
1299             status = ar6000_transfer_bin_file(ar, AR6K_OTP_FILE, address, TRUE);
1300             if (status == A_OK) {
1301                 /* Execute the OTP code */
1302                 param = 0;
1303                 AR6K_APP_START_OVERRIDE_ADDRESS(address, ar->arVersion.target_ver);
1304                 bmifn(BMIExecute(ar->arHifDevice, address, &param));
1305             } else if (status != A_ENOENT) {
1306                 return A_ERROR;
1307             } 
1308         } else {
1309             AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("Programming of board data for chip %d not supported\n", ar->arTargetType));
1310             return A_ERROR;
1311         }
1312
1313         /* Download Target firmware */
1314         AR6K_DATA_DOWNLOAD_ADDRESS(address, ar->arVersion.target_ver);
1315         if ((ar6000_transfer_bin_file(ar, AR6K_FIRMWARE_FILE, address, TRUE)) != A_OK) {
1316             return A_ERROR;
1317         }
1318
1319         /* Set starting address for firmware */
1320         AR6K_APP_START_OVERRIDE_ADDRESS(address, ar->arVersion.target_ver);
1321         bmifn(BMISetAppStart(ar->arHifDevice, address));
1322
1323         /* Apply the patches */
1324         AR6K_PATCH_DOWNLOAD_ADDRESS(address, ar->arVersion.target_ver);
1325         if ((ar6000_transfer_bin_file(ar, AR6K_PATCH_FILE, address, FALSE)) != A_OK) {
1326             return A_ERROR;
1327         }
1328
1329         param = address;
1330         bmifn(BMIWriteMemory(ar->arHifDevice, HOST_INTEREST_ITEM_ADDRESS(ar, hi_dset_list_head), (A_UCHAR *)&param, 4));
1331
1332         if (ar->arTargetType == TARGET_TYPE_AR6003) {
1333             if (ar->arVersion.target_ver == AR6003_REV1_VERSION) {
1334                 /* Reserve 5.5K of RAM */
1335                 param = 5632;
1336             } else { /* AR6003_REV2_VERSION */
1337                 /* Reserve 6.5K of RAM */
1338                 param = 6656;
1339             }
1340             bmifn(BMIWriteMemory(ar->arHifDevice, HOST_INTEREST_ITEM_ADDRESS(ar, hi_end_RAM_reserve_sz), (A_UCHAR *)&param, 4));
1341         }
1342
1343         /* Restore system sleep */
1344         address = RTC_BASE_ADDRESS + SYSTEM_SLEEP_ADDRESS;
1345         bmifn(BMIWriteSOCRegister(ar->arHifDevice, address, sleep));
1346
1347         address = MBOX_BASE_ADDRESS + LOCAL_SCRATCH_ADDRESS;
1348         param = options | 0x20;
1349         bmifn(BMIWriteSOCRegister(ar->arHifDevice, address, param));
1350
1351         if (ar->arTargetType == TARGET_TYPE_AR6003) {
1352             /* Configure GPIO AR6003 UART */
1353 #ifndef CONFIG_AR600x_DEBUG_UART_TX_PIN
1354 #define CONFIG_AR600x_DEBUG_UART_TX_PIN 8
1355 #endif
1356             param = CONFIG_AR600x_DEBUG_UART_TX_PIN;
1357             bmifn(BMIWriteMemory(ar->arHifDevice, HOST_INTEREST_ITEM_ADDRESS(ar, hi_dbg_uart_txpin), (A_UCHAR *)&param, 4));
1358
1359 #if (CONFIG_AR600x_DEBUG_UART_TX_PIN == 23)
1360             {
1361                 address = GPIO_BASE_ADDRESS + CLOCK_GPIO_ADDRESS;
1362                 bmifn(BMIReadSOCRegister(ar->arHifDevice, address, &param));
1363                 param |= CLOCK_GPIO_BT_CLK_OUT_EN_SET(1);
1364                 bmifn(BMIWriteSOCRegister(ar->arHifDevice, address, param));
1365             }
1366 #endif
1367
1368             /* Configure GPIO for BT Reset */
1369 #ifdef ATH6KL_CONFIG_GPIO_BT_RESET
1370 #define CONFIG_AR600x_BT_RESET_PIN      0x16
1371             param = CONFIG_AR600x_BT_RESET_PIN;
1372             bmifn(BMIWriteMemory(ar->arHifDevice, HOST_INTEREST_ITEM_ADDRESS(ar, hi_hci_uart_support_pins), (A_UCHAR *)&param, 4));
1373 #endif /* ATH6KL_CONFIG_GPIO_BT_RESET */
1374
1375             /* Configure UART flow control polarity */
1376 #ifndef CONFIG_ATH6KL_BT_UART_FC_POLARITY
1377 #define CONFIG_ATH6KL_BT_UART_FC_POLARITY 0
1378 #endif
1379
1380 #if (CONFIG_ATH6KL_BT_UART_FC_POLARITY == 1)
1381             if (ar->arVersion.target_ver == AR6003_REV2_VERSION) {
1382                 param = ((CONFIG_ATH6KL_BT_UART_FC_POLARITY << 1) & 0x2);
1383                 bmifn(BMIWriteMemory(ar->arHifDevice, HOST_INTEREST_ITEM_ADDRESS(ar, hi_hci_uart_pwr_mgmt_params), (A_UCHAR *)&param, 4));
1384             }
1385 #endif /* CONFIG_ATH6KL_BT_UART_FC_POLARITY */
1386         }
1387
1388 #ifdef HTC_RAW_INTERFACE
1389         if (!eppingtest && bypasswmi) {
1390             /* Don't run BMIDone for ART mode and force resetok=0 */
1391             resetok = 0;
1392             msleep(1000);
1393         }
1394 #endif /* HTC_RAW_INTERFACE */
1395
1396 #endif /* INIT_MODE_DRV_ENABLED */
1397     }
1398
1399     return A_OK;
1400 }
1401
1402 A_STATUS
1403 ar6000_configure_target(AR_SOFTC_T *ar)
1404 {
1405     A_UINT32 param;
1406     if (enableuartprint) {
1407         param = 1;
1408         if (BMIWriteMemory(ar->arHifDevice,
1409                            HOST_INTEREST_ITEM_ADDRESS(ar, hi_serial_enable),
1410                            (A_UCHAR *)&param,
1411                            4)!= A_OK)
1412         {
1413              AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("BMIWriteMemory for enableuartprint failed \n"));
1414              return A_ERROR;
1415         }
1416         AR_DEBUG_PRINTF(ATH_DEBUG_INFO,("Serial console prints enabled\n"));
1417     }
1418
1419     /* Tell target which HTC version it is used*/
1420     param = HTC_PROTOCOL_VERSION;
1421     if (BMIWriteMemory(ar->arHifDevice,
1422                        HOST_INTEREST_ITEM_ADDRESS(ar, hi_app_host_interest),
1423                        (A_UCHAR *)&param,
1424                        4)!= A_OK)
1425     {
1426          AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("BMIWriteMemory for htc version failed \n"));
1427          return A_ERROR;
1428     }
1429
1430 #ifdef CONFIG_HOST_TCMD_SUPPORT
1431     if(testmode) {
1432         ar->arTargetMode = AR6000_TCMD_MODE;
1433     }else {
1434         ar->arTargetMode = AR6000_WLAN_MODE;
1435     }
1436 #endif
1437     if (enabletimerwar) {
1438         A_UINT32 param;
1439
1440         if (BMIReadMemory(ar->arHifDevice,
1441             HOST_INTEREST_ITEM_ADDRESS(ar, hi_option_flag),
1442             (A_UCHAR *)&param,
1443             4)!= A_OK)
1444         {
1445             AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("BMIReadMemory for enabletimerwar failed \n"));
1446             return A_ERROR;
1447         }
1448
1449         param |= HI_OPTION_TIMER_WAR;
1450
1451         if (BMIWriteMemory(ar->arHifDevice,
1452             HOST_INTEREST_ITEM_ADDRESS(ar, hi_option_flag),
1453             (A_UCHAR *)&param,
1454             4) != A_OK)
1455         {
1456             AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("BMIWriteMemory for enabletimerwar failed \n"));
1457             return A_ERROR;
1458         }
1459         AR_DEBUG_PRINTF(ATH_DEBUG_INFO,("Timer WAR enabled\n"));
1460     }
1461
1462     /* set the firmware mode to STA/IBSS/AP */
1463     {
1464         A_UINT32 param;
1465
1466         if (BMIReadMemory(ar->arHifDevice,
1467             HOST_INTEREST_ITEM_ADDRESS(ar, hi_option_flag),
1468             (A_UCHAR *)&param,
1469             4)!= A_OK)
1470         {
1471             AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("BMIReadMemory for setting fwmode failed \n"));
1472             return A_ERROR;
1473         }
1474
1475         param |= (fwmode << HI_OPTION_FW_MODE_SHIFT);
1476
1477         if (BMIWriteMemory(ar->arHifDevice,
1478             HOST_INTEREST_ITEM_ADDRESS(ar, hi_option_flag),
1479             (A_UCHAR *)&param,
1480             4) != A_OK)
1481         {
1482             AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("BMIWriteMemory for setting fwmode failed \n"));
1483             return A_ERROR;
1484         }
1485         AR_DEBUG_PRINTF(ATH_DEBUG_INFO,("Firmware mode set\n"));
1486     }
1487
1488 #ifdef ATH6KL_DISABLE_TARGET_DBGLOGS
1489     {
1490         A_UINT32 param;
1491
1492         if (BMIReadMemory(ar->arHifDevice,
1493             HOST_INTEREST_ITEM_ADDRESS(ar, hi_option_flag),
1494             (A_UCHAR *)&param,
1495             4)!= A_OK)
1496         {
1497             AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("BMIReadMemory for disabling debug logs failed\n"));
1498             return A_ERROR;
1499         }
1500
1501         param |= HI_OPTION_DISABLE_DBGLOG;
1502
1503         if (BMIWriteMemory(ar->arHifDevice,
1504             HOST_INTEREST_ITEM_ADDRESS(ar, hi_option_flag),
1505             (A_UCHAR *)&param,
1506             4) != A_OK)
1507         {
1508             AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("BMIWriteMemory for HI_OPTION_DISABLE_DBGLOG\n"));
1509             return A_ERROR;
1510         }
1511         AR_DEBUG_PRINTF(ATH_DEBUG_INFO,("Firmware mode set\n"));
1512     }
1513 #endif /* ATH6KL_DISABLE_TARGET_DBGLOGS */
1514
1515     /* 
1516      * Hardcode the address use for the extended board data 
1517      * Ideally this should be pre-allocate by the OS at boot time
1518      * But since it is a new feature and board data is loaded 
1519      * at init time, we have to workaround this from host.
1520      * It is difficult to patch the firmware boot code,
1521      * but possible in theory.
1522      */
1523     if (ar->arTargetType == TARGET_TYPE_AR6003) {
1524         param = AR6003_BOARD_EXT_DATA_ADDRESS; 
1525         if (BMIWriteMemory(ar->arHifDevice,
1526             HOST_INTEREST_ITEM_ADDRESS(ar, hi_board_ext_data),
1527             (A_UCHAR *)&param,
1528             4) != A_OK)
1529         {
1530             AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("BMIWriteMemory for hi_board_ext_data failed \n"));
1531             return A_ERROR;
1532         }
1533     }
1534
1535
1536         /* since BMIInit is called in the driver layer, we have to set the block
1537          * size here for the target */
1538
1539     if (A_FAILED(ar6000_set_htc_params(ar->arHifDevice,
1540                                        ar->arTargetType,
1541                                        mbox_yield_limit,
1542                                        0 /* use default number of control buffers */
1543                                        ))) {
1544         return A_ERROR;
1545     }
1546
1547     if (setupbtdev != 0) {
1548         if (A_FAILED(ar6000_set_hci_bridge_flags(ar->arHifDevice,
1549                                                  ar->arTargetType,
1550                                                  setupbtdev))) {
1551             return A_ERROR;
1552         }
1553     }
1554     return A_OK;
1555 }
1556
1557 static void
1558 init_netdev(struct net_device *dev, char *name)
1559 {
1560     dev->netdev_ops = &ar6000_netdev_ops;
1561     dev->watchdog_timeo = AR6000_TX_TIMEOUT;
1562     dev->wireless_handlers = &ath_iw_handler_def;
1563
1564     ath_iw_handler_def.get_wireless_stats = ar6000_get_iwstats; /*Displayed via proc fs */
1565
1566    /*
1567     * We need the OS to provide us with more headroom in order to
1568     * perform dix to 802.3, WMI header encap, and the HTC header
1569     */
1570     if (processDot11Hdr) {
1571         dev->hard_header_len = sizeof(struct ieee80211_qosframe) + sizeof(ATH_LLC_SNAP_HDR) + sizeof(WMI_DATA_HDR) + HTC_HEADER_LEN + WMI_MAX_TX_META_SZ + LINUX_HACK_FUDGE_FACTOR;
1572     } else {
1573         dev->hard_header_len = ETH_HLEN + sizeof(ATH_LLC_SNAP_HDR) +
1574             sizeof(WMI_DATA_HDR) + HTC_HEADER_LEN + WMI_MAX_TX_META_SZ + LINUX_HACK_FUDGE_FACTOR;
1575     }
1576
1577     if (name[0])
1578     {
1579         strcpy(dev->name, name);
1580     }
1581
1582 #ifdef SET_MODULE_OWNER
1583     SET_MODULE_OWNER(dev);
1584 #endif
1585
1586 #ifdef CONFIG_CHECKSUM_OFFLOAD
1587     if(csumOffload){
1588         dev->features |= NETIF_F_IP_CSUM; /*advertise kernel capability to do TCP/UDP CSUM offload for IPV4*/
1589     }
1590 #endif
1591
1592     return;
1593 }
1594
1595 /*
1596  * HTC Event handlers
1597  */
1598 static A_STATUS
1599 ar6000_avail_ev(void *context, void *hif_handle)
1600 {
1601     int i;
1602     struct net_device *dev;
1603     void *ar_netif;
1604     AR_SOFTC_T *ar;
1605     int device_index = 0;
1606     HTC_INIT_INFO  htcInfo;
1607 #ifdef ATH6K_CONFIG_CFG80211
1608     struct wireless_dev *wdev;
1609 #endif /* ATH6K_CONFIG_CFG80211 */
1610     A_STATUS init_status = A_OK;
1611
1612     AR_DEBUG_PRINTF(ATH_DEBUG_INFO,("ar6000_available\n"));
1613
1614     for (i=0; i < MAX_AR6000; i++) {
1615         if (ar6000_devices[i] == NULL) {
1616             break;
1617         }
1618     }
1619
1620     if (i == MAX_AR6000) {
1621         AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("ar6000_available: max devices reached\n"));
1622         return A_ERROR;
1623     }
1624
1625     /* Save this. It gives a bit better readability especially since */
1626     /* we use another local "i" variable below.                      */
1627     device_index = i;
1628
1629 #ifdef ATH6K_CONFIG_CFG80211
1630     wdev = ar6k_cfg80211_init(NULL);
1631     if (IS_ERR(wdev)) {
1632         AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("%s: ar6k_cfg80211_init failed\n", __func__));
1633         return A_ERROR;
1634     }
1635     ar_netif = wdev_priv(wdev);
1636 #else
1637     dev = alloc_etherdev(sizeof(AR_SOFTC_T));
1638     if (dev == NULL) {
1639         AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("ar6000_available: can't alloc etherdev\n"));
1640         return A_ERROR;
1641     }
1642     ether_setup(dev);
1643     ar_netif = ar6k_priv(dev);
1644 #endif /* ATH6K_CONFIG_CFG80211 */
1645
1646     if (ar_netif == NULL) {
1647         AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("%s: Can't allocate ar6k priv memory\n", __func__));
1648         return A_ERROR;
1649     }
1650
1651     A_MEMZERO(ar_netif, sizeof(AR_SOFTC_T));
1652     ar = (AR_SOFTC_T *)ar_netif;
1653
1654 #ifdef ATH6K_CONFIG_CFG80211
1655     ar->wdev = wdev;
1656     wdev->iftype = NL80211_IFTYPE_STATION;
1657
1658     dev = alloc_netdev_mq(0, "wlan%d", ether_setup, 1);
1659     if (!dev) {
1660         printk(KERN_CRIT "AR6K: no memory for network device instance\n");
1661         ar6k_cfg80211_deinit(ar);
1662         return A_ERROR;
1663     }
1664
1665     dev->ieee80211_ptr = wdev;
1666     SET_NETDEV_DEV(dev, wiphy_dev(wdev->wiphy));
1667     wdev->netdev = dev;
1668     ar->arNetworkType = INFRA_NETWORK;
1669 #endif /* ATH6K_CONFIG_CFG80211 */
1670
1671     init_netdev(dev, ifname);
1672
1673 #ifdef SET_NETDEV_DEV
1674     if (ar_netif) { 
1675         HIF_DEVICE_OS_DEVICE_INFO osDevInfo;
1676         A_MEMZERO(&osDevInfo, sizeof(osDevInfo));
1677         if ( A_SUCCESS( HIFConfigureDevice(hif_handle, HIF_DEVICE_GET_OS_DEVICE,
1678                         &osDevInfo, sizeof(osDevInfo))) ) {
1679             SET_NETDEV_DEV(dev, osDevInfo.pOSDevice);
1680         }
1681     }
1682 #endif 
1683
1684     ar->arNetDev             = dev;
1685     ar->arHifDevice          = hif_handle;
1686     ar->arWlanState          = WLAN_ENABLED;
1687     ar->arDeviceIndex        = device_index;
1688
1689     ar->arWlanPowerState     = WLAN_POWER_STATE_ON;
1690     ar->arWlanOff            = FALSE;   /* We are in ON state */
1691 #ifdef CONFIG_PM
1692     ar->arWowState           = WLAN_WOW_STATE_NONE;
1693     ar->arBTOff              = TRUE;   /* BT chip assumed to be OFF */
1694     ar->arBTSharing          = WLAN_CONFIG_BT_SHARING; 
1695     ar->arWlanOffConfig      = WLAN_CONFIG_WLAN_OFF;
1696     ar->arSuspendConfig      = WLAN_CONFIG_PM_SUSPEND;
1697     ar->arWow2Config         = WLAN_CONFIG_PM_WOW2;
1698 #endif /* CONFIG_PM */
1699
1700     A_INIT_TIMER(&ar->arHBChallengeResp.timer, ar6000_detect_error, dev);
1701     ar->arHBChallengeResp.seqNum = 0;
1702     ar->arHBChallengeResp.outstanding = FALSE;
1703     ar->arHBChallengeResp.missCnt = 0;
1704     ar->arHBChallengeResp.frequency = AR6000_HB_CHALLENGE_RESP_FREQ_DEFAULT;
1705     ar->arHBChallengeResp.missThres = AR6000_HB_CHALLENGE_RESP_MISS_THRES_DEFAULT;
1706
1707     ar6000_init_control_info(ar);
1708     init_waitqueue_head(&arEvent);
1709     sema_init(&ar->arSem, 1);
1710     ar->bIsDestroyProgress = FALSE;
1711
1712     INIT_HTC_PACKET_QUEUE(&ar->amsdu_rx_buffer_queue);
1713
1714 #ifdef ADAPTIVE_POWER_THROUGHPUT_CONTROL
1715     A_INIT_TIMER(&aptcTimer, aptcTimerHandler, ar);
1716 #endif /* ADAPTIVE_POWER_THROUGHPUT_CONTROL */
1717
1718     A_INIT_TIMER(&ar->disconnect_timer, disconnect_timer_handler, dev);
1719
1720     BMIInit();
1721
1722     if (bmienable) {
1723         ar6000_sysfs_bmi_init(ar);
1724     }
1725
1726     {
1727         struct bmi_target_info targ_info;
1728
1729         if (BMIGetTargetInfo(ar->arHifDevice, &targ_info) != A_OK) {
1730             init_status = A_ERROR;
1731             goto avail_ev_failed;
1732         }
1733
1734         ar->arVersion.target_ver = targ_info.target_ver;
1735         ar->arTargetType = targ_info.target_type;
1736
1737             /* do any target-specific preparation that can be done through BMI */
1738         if (ar6000_prepare_target(ar->arHifDevice,
1739                                   targ_info.target_type,
1740                                   targ_info.target_ver) != A_OK) {
1741             init_status = A_ERROR;
1742             goto avail_ev_failed;
1743         }
1744
1745     }
1746
1747     if (ar6000_configure_target(ar) != A_OK) {
1748             init_status = A_ERROR;
1749             goto avail_ev_failed;
1750     }
1751
1752     A_MEMZERO(&htcInfo,sizeof(htcInfo));
1753     htcInfo.pContext = ar;
1754     htcInfo.TargetFailure = ar6000_target_failure;
1755
1756     ar->arHtcTarget = HTCCreate(ar->arHifDevice,&htcInfo);
1757
1758     if (ar->arHtcTarget == NULL) {
1759         init_status = A_ERROR;
1760         goto avail_ev_failed;
1761     }
1762
1763     spin_lock_init(&ar->arLock);
1764
1765 #ifdef WAPI_ENABLE
1766     ar->arWapiEnable = 0;
1767 #endif
1768
1769
1770 #ifdef CONFIG_CHECKSUM_OFFLOAD
1771     if(csumOffload){
1772         /*if external frame work is also needed, change and use an extended rxMetaVerion*/
1773         ar->rxMetaVersion=WMI_META_VERSION_2;
1774     }
1775 #endif
1776
1777 #ifdef ATH_AR6K_11N_SUPPORT
1778     if((ar->aggr_cntxt = aggr_init(ar6000_alloc_netbufs)) == NULL) {
1779             AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("%s() Failed to initialize aggr.\n", __func__));
1780             init_status = A_ERROR;
1781             goto avail_ev_failed;
1782     }
1783
1784     aggr_register_rx_dispatcher(ar->aggr_cntxt, (void *)dev, ar6000_deliver_frames_to_nw_stack);
1785 #endif
1786
1787     HIFClaimDevice(ar->arHifDevice, ar);
1788
1789     /* We only register the device in the global list if we succeed. */
1790     /* If the device is in the global list, it will be destroyed     */
1791     /* when the module is unloaded.                                  */
1792     ar6000_devices[device_index] = dev;
1793
1794     /* Don't install the init function if BMI is requested */
1795     if (!bmienable) {
1796         ar6000_netdev_ops.ndo_init = ar6000_init;
1797     } else {
1798         AR_DEBUG_PRINTF(ATH_DEBUG_INFO, ("BMI enabled: %d\n", wlaninitmode));
1799         if ((wlaninitmode == WLAN_INIT_MODE_UDEV) ||
1800             (wlaninitmode == WLAN_INIT_MODE_DRV))
1801         {
1802             A_STATUS status = A_OK;
1803             do {
1804                 if ((status = ar6000_sysfs_bmi_get_config(ar, wlaninitmode)) != A_OK)
1805                 {
1806                     AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("ar6000_avail: ar6000_sysfs_bmi_get_config failed\n"));
1807                     break;
1808                 }
1809 #ifdef HTC_RAW_INTERFACE
1810                 break; /* Don't call ar6000_init for ART */
1811 #endif 
1812                 rtnl_lock();
1813                 status = (ar6000_init(dev)==0) ? A_OK : A_ERROR;
1814                 rtnl_unlock();
1815                 if (status != A_OK) {
1816                     AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("ar6000_avail: ar6000_init\n"));
1817                 }
1818             } while (FALSE);
1819
1820             if (status != A_OK) {
1821                 init_status = status;
1822                 goto avail_ev_failed;
1823             }
1824         }
1825     }
1826
1827     /* This runs the init function if registered */
1828     if (register_netdev(dev)) {
1829         AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("ar6000_avail: register_netdev failed\n"));
1830         ar6000_destroy(dev, 0);
1831         return A_ERROR;
1832     }
1833
1834         is_netdev_registered = 1;
1835
1836 #ifdef CONFIG_AP_VIRTUAL_ADAPTER_SUPPORT
1837     arApNetDev = NULL;
1838 #endif /* CONFIG_AP_VIRTUAL_ADAPTER_SUPPORT */
1839     AR_DEBUG_PRINTF(ATH_DEBUG_INFO,("ar6000_avail: name=%s hifdevice=0x%lx, dev=0x%lx (%d), ar=0x%lx\n",
1840                     dev->name, (unsigned long)ar->arHifDevice, (unsigned long)dev, device_index,
1841                     (unsigned long)ar));
1842
1843 avail_ev_failed :
1844     if (A_FAILED(init_status)) {
1845         if (bmienable) { 
1846             ar6000_sysfs_bmi_deinit(ar);  
1847         }
1848     }
1849
1850     return init_status;
1851 }
1852
1853 static void ar6000_target_failure(void *Instance, A_STATUS Status)
1854 {
1855     AR_SOFTC_T *ar = (AR_SOFTC_T *)Instance;
1856     WMI_TARGET_ERROR_REPORT_EVENT errEvent;
1857     static A_BOOL sip = FALSE;
1858
1859     if (Status != A_OK) {
1860
1861         printk(KERN_ERR "ar6000_target_failure: target asserted \n");
1862
1863         if (timer_pending(&ar->arHBChallengeResp.timer)) {
1864             A_UNTIMEOUT(&ar->arHBChallengeResp.timer);
1865         }
1866
1867         /* try dumping target assertion information (if any) */
1868         ar6000_dump_target_assert_info(ar->arHifDevice,ar->arTargetType);
1869
1870         /*
1871          * Fetch the logs from the target via the diagnostic
1872          * window.
1873          */
1874         ar6000_dbglog_get_debug_logs(ar);
1875
1876         /* Report the error only once */
1877         if (!sip) {
1878             sip = TRUE;
1879             errEvent.errorVal = WMI_TARGET_COM_ERR |
1880                                 WMI_TARGET_FATAL_ERR;
1881             ar6000_send_event_to_app(ar, WMI_ERROR_REPORT_EVENTID,
1882                                      (A_UINT8 *)&errEvent,
1883                                      sizeof(WMI_TARGET_ERROR_REPORT_EVENT));
1884         }
1885     }
1886 }
1887
1888 static A_STATUS
1889 ar6000_unavail_ev(void *context, void *hif_handle)
1890 {
1891     AR_SOFTC_T *ar = (AR_SOFTC_T *)context;
1892         /* NULL out it's entry in the global list */
1893     ar6000_devices[ar->arDeviceIndex] = NULL;
1894     ar6000_destroy(ar->arNetDev, 1);
1895
1896     return A_OK;
1897 }
1898
1899 void
1900 ar6000_restart_endpoint(struct net_device *dev)
1901 {
1902     A_STATUS status = A_OK;
1903     AR_SOFTC_T *ar = (AR_SOFTC_T *)ar6k_priv(dev);
1904
1905     BMIInit();
1906     do {
1907         if ( (status=ar6000_configure_target(ar))!=A_OK)
1908             break;
1909         if ( (status=ar6000_sysfs_bmi_get_config(ar, wlaninitmode)) != A_OK)
1910         {
1911             AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("ar6000_avail: ar6000_sysfs_bmi_get_config failed\n"));
1912             break;
1913         }
1914         rtnl_lock();
1915         status = (ar6000_init(dev)==0) ? A_OK : A_ERROR;
1916         rtnl_unlock();
1917
1918         if (status!=A_OK) {
1919             break;
1920         }
1921         if (ar->arSsidLen && ar->arWlanState == WLAN_ENABLED) {
1922             ar6000_connect_to_ap(ar);
1923         }  
1924     } while (0);
1925
1926     if (status==A_OK) {
1927         return;
1928     }
1929
1930     ar6000_devices[ar->arDeviceIndex] = NULL;
1931     ar6000_destroy(ar->arNetDev, 1);
1932 }
1933
1934 void
1935 ar6000_stop_endpoint(struct net_device *dev, A_BOOL keepprofile, A_BOOL getdbglogs)
1936 {
1937     AR_SOFTC_T *ar = (AR_SOFTC_T *)ar6k_priv(dev);
1938
1939     /* Stop the transmit queues */
1940     netif_stop_queue(dev);
1941
1942     /* Disable the target and the interrupts associated with it */
1943     if (ar->arWmiReady == TRUE)
1944     {
1945         if (!bypasswmi)
1946         {
1947             if (ar->arConnected == TRUE || ar->arConnectPending == TRUE)
1948             {
1949                 AR_DEBUG_PRINTF(ATH_DEBUG_INFO,("%s(): Disconnect\n", __func__));
1950                 if (!keepprofile) {
1951                     AR6000_SPIN_LOCK(&ar->arLock, 0);
1952                     ar6000_init_profile_info(ar);
1953                     AR6000_SPIN_UNLOCK(&ar->arLock, 0);
1954                 }
1955                 wmi_disconnect_cmd(ar->arWmi);
1956             }
1957
1958             A_UNTIMEOUT(&ar->disconnect_timer);
1959
1960             if (getdbglogs) {
1961                 ar6000_dbglog_get_debug_logs(ar);
1962             }
1963
1964             ar->arWmiReady  = FALSE;
1965             wmi_shutdown(ar->arWmi);
1966             ar->arWmiEnabled = FALSE;
1967             ar->arWmi = NULL;
1968             /* 
1969              * After wmi_shudown all WMI events will be dropped.
1970              * We need to cleanup the buffers allocated in AP mode
1971              * and give disconnect notification to stack, which usually
1972              * happens in the disconnect_event. 
1973              * Simulate the disconnect_event by calling the function directly.
1974              * Sometimes disconnect_event will be received when the debug logs 
1975              * are collected.
1976              */
1977             if (ar->arConnected == TRUE || ar->arConnectPending == TRUE) {
1978                 if(ar->arNetworkType & AP_NETWORK) {
1979                     ar6000_disconnect_event(ar, DISCONNECT_CMD, bcast_mac, 0, NULL, 0);
1980                 } else {
1981                     ar6000_disconnect_event(ar, DISCONNECT_CMD, ar->arBssid, 0, NULL, 0);
1982                 }
1983                 ar->arConnected = FALSE;
1984                 ar->arConnectPending = FALSE;
1985             }
1986 #ifdef USER_KEYS
1987             ar->user_savedkeys_stat = USER_SAVEDKEYS_STAT_INIT;
1988             ar->user_key_ctrl      = 0;
1989 #endif
1990         }
1991
1992          AR_DEBUG_PRINTF(ATH_DEBUG_INFO,("%s(): WMI stopped\n", __func__));
1993     }
1994     else
1995     {
1996         AR_DEBUG_PRINTF(ATH_DEBUG_INFO,("%s(): WMI not ready 0x%lx 0x%lx\n",
1997             __func__, (unsigned long) ar, (unsigned long) ar->arWmi));
1998
1999         /* Shut down WMI if we have started it */
2000         if(ar->arWmiEnabled == TRUE)
2001         {
2002             AR_DEBUG_PRINTF(ATH_DEBUG_INFO,("%s(): Shut down WMI\n", __func__));
2003             wmi_shutdown(ar->arWmi);
2004             ar->arWmiEnabled = FALSE;
2005             ar->arWmi = NULL;
2006         }
2007     }
2008
2009     if (ar->arHtcTarget != NULL) {
2010 #ifdef EXPORT_HCI_BRIDGE_INTERFACE
2011         if (NULL != ar6kHciTransCallbacks.cleanupTransport) {
2012             ar6kHciTransCallbacks.cleanupTransport(NULL);
2013         }
2014 #else
2015         // FIXME: workaround to reset BT's UART baud rate to default
2016         if (NULL != ar->exitCallback) {
2017             AR3K_CONFIG_INFO ar3kconfig;
2018             A_STATUS status;
2019
2020             A_MEMZERO(&ar3kconfig,sizeof(ar3kconfig));
2021             ar6000_set_default_ar3kconfig(ar, (void *)&ar3kconfig);
2022             status = ar->exitCallback(&ar3kconfig);
2023             if (A_OK != status) {
2024                 AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("Failed to reset AR3K baud rate! \n"));
2025             }
2026         }
2027         // END workaround
2028         if (setuphci)
2029                 ar6000_cleanup_hci(ar);
2030 #endif
2031 #ifdef EXPORT_HCI_PAL_INTERFACE
2032         if (setuphcipal && (NULL != ar6kHciPalCallbacks_g.cleanupTransport)) {
2033            ar6kHciPalCallbacks_g.cleanupTransport(ar);
2034         }
2035 #else
2036                                 /* cleanup hci pal driver data structures */
2037         if(setuphcipal)
2038           ar6k_cleanup_hci_pal(ar);
2039 #endif
2040         AR_DEBUG_PRINTF(ATH_DEBUG_INFO,(" Shutting down HTC .... \n"));
2041         /* stop HTC */
2042         HTCStop(ar->arHtcTarget);
2043     }
2044
2045     if (resetok) {
2046         /* try to reset the device if we can
2047          * The driver may have been configure NOT to reset the target during
2048          * a debug session */
2049         AR_DEBUG_PRINTF(ATH_DEBUG_INFO,(" Attempting to reset target on instance destroy.... \n"));
2050         if (ar->arHifDevice != NULL) {
2051             A_BOOL coldReset = (ar->arTargetType == TARGET_TYPE_AR6003) ? TRUE: FALSE;
2052             ar6000_reset_device(ar->arHifDevice, ar->arTargetType, TRUE, coldReset);
2053         }
2054     } else {
2055         AR_DEBUG_PRINTF(ATH_DEBUG_INFO,(" Host does not want target reset. \n"));
2056     }
2057        /* Done with cookies */
2058     ar6000_cookie_cleanup(ar);
2059 }
2060 /*
2061  * We need to differentiate between the surprise and planned removal of the
2062  * device because of the following consideration:
2063  * - In case of surprise removal, the hcd already frees up the pending
2064  *   for the device and hence there is no need to unregister the function
2065  *   driver inorder to get these requests. For planned removal, the function
2066  *   driver has to explictly unregister itself to have the hcd return all the
2067  *   pending requests before the data structures for the devices are freed up.
2068  *   Note that as per the current implementation, the function driver will
2069  *   end up releasing all the devices since there is no API to selectively
2070  *   release a particular device.
2071  * - Certain commands issued to the target can be skipped for surprise
2072  *   removal since they will anyway not go through.
2073  */
2074 void
2075 ar6000_destroy(struct net_device *dev, unsigned int unregister)
2076 {
2077     AR_SOFTC_T *ar;
2078
2079     AR_DEBUG_PRINTF(ATH_DEBUG_INFO,("+ar6000_destroy \n"));
2080     
2081     if((dev == NULL) || ((ar = ar6k_priv(dev)) == NULL))
2082     {
2083         AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("%s(): Failed to get device structure.\n", __func__));
2084         return;
2085     }
2086
2087     ar->bIsDestroyProgress = TRUE;
2088
2089     if (down_interruptible(&ar->arSem)) {
2090         AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("%s(): down_interruptible failed \n", __func__));
2091         return;
2092     }
2093
2094     if (ar->arWlanPowerState != WLAN_POWER_STATE_CUT_PWR) {
2095         /* only stop endpoint if we are not stop it in suspend_ev */
2096         ar6000_stop_endpoint(dev, FALSE, TRUE);
2097     } else {
2098         /* clear up the platform power state before rmmod */
2099         plat_setup_power(1,0);
2100     }
2101
2102     ar->arWlanState = WLAN_DISABLED;
2103     if (ar->arHtcTarget != NULL) {
2104         /* destroy HTC */
2105         HTCDestroy(ar->arHtcTarget);
2106     }
2107     if (ar->arHifDevice != NULL) {
2108         /*release the device so we do not get called back on remove incase we
2109          * we're explicity destroyed by module unload */
2110         HIFReleaseDevice(ar->arHifDevice);
2111         HIFShutDownDevice(ar->arHifDevice);
2112     }
2113 #ifdef ATH_AR6K_11N_SUPPORT
2114     aggr_module_destroy(ar->aggr_cntxt);
2115 #endif
2116
2117        /* Done with cookies */
2118     ar6000_cookie_cleanup(ar);
2119
2120         /* cleanup any allocated AMSDU buffers */
2121     ar6000_cleanup_amsdu_rxbufs(ar);
2122
2123     if (bmienable) {
2124         ar6000_sysfs_bmi_deinit(ar);
2125     }
2126
2127     /* Cleanup BMI */
2128     BMICleanup();
2129
2130     /* Clear the tx counters */
2131     memset(tx_attempt, 0, sizeof(tx_attempt));
2132     memset(tx_post, 0, sizeof(tx_post));
2133     memset(tx_complete, 0, sizeof(tx_complete));
2134
2135 #ifdef HTC_RAW_INTERFACE
2136     if (ar->arRawHtc) {
2137         A_FREE(ar->arRawHtc);
2138         ar->arRawHtc = NULL;
2139     }
2140 #endif 
2141     /* Free up the device data structure */
2142     if (unregister && is_netdev_registered) {           
2143         unregister_netdev(dev);
2144         is_netdev_registered = 0;
2145     }
2146     free_netdev(dev);
2147
2148 #ifdef ATH6K_CONFIG_CFG80211
2149     ar6k_cfg80211_deinit(ar);
2150 #endif /* ATH6K_CONFIG_CFG80211 */
2151
2152 #ifdef CONFIG_AP_VIRTUL_ADAPTER_SUPPORT
2153     ar6000_remove_ap_interface();
2154 #endif /*CONFIG_AP_VIRTUAL_ADAPTER_SUPPORT */
2155
2156     AR_DEBUG_PRINTF(ATH_DEBUG_INFO,("-ar6000_destroy \n"));
2157 }
2158
2159 static void disconnect_timer_handler(unsigned long ptr)
2160 {
2161     struct net_device *dev = (struct net_device *)ptr;
2162     AR_SOFTC_T *ar = (AR_SOFTC_T *)ar6k_priv(dev);
2163
2164     A_UNTIMEOUT(&ar->disconnect_timer);
2165
2166     ar6000_init_profile_info(ar);
2167     wmi_disconnect_cmd(ar->arWmi);
2168 }
2169
2170 static void ar6000_detect_error(unsigned long ptr)
2171 {
2172     struct net_device *dev = (struct net_device *)ptr;
2173     AR_SOFTC_T *ar = (AR_SOFTC_T *)ar6k_priv(dev);
2174     WMI_TARGET_ERROR_REPORT_EVENT errEvent;
2175
2176     AR6000_SPIN_LOCK(&ar->arLock, 0);
2177
2178     if (ar->arHBChallengeResp.outstanding) {
2179         ar->arHBChallengeResp.missCnt++;
2180     } else {
2181         ar->arHBChallengeResp.missCnt = 0;
2182     }
2183
2184     if (ar->arHBChallengeResp.missCnt > ar->arHBChallengeResp.missThres) {
2185         /* Send Error Detect event to the application layer and do not reschedule the error detection module timer */
2186         ar->arHBChallengeResp.missCnt = 0;
2187         ar->arHBChallengeResp.seqNum = 0;
2188         errEvent.errorVal = WMI_TARGET_COM_ERR | WMI_TARGET_FATAL_ERR;
2189         AR6000_SPIN_UNLOCK(&ar->arLock, 0);
2190         ar6000_send_event_to_app(ar, WMI_ERROR_REPORT_EVENTID,
2191                                  (A_UINT8 *)&errEvent,
2192                                  sizeof(WMI_TARGET_ERROR_REPORT_EVENT));
2193         return;
2194     }
2195
2196     /* Generate the sequence number for the next challenge */
2197     ar->arHBChallengeResp.seqNum++;
2198     ar->arHBChallengeResp.outstanding = TRUE;
2199
2200     AR6000_SPIN_UNLOCK(&ar->arLock, 0);
2201
2202     /* Send the challenge on the control channel */
2203     if (wmi_get_challenge_resp_cmd(ar->arWmi, ar->arHBChallengeResp.seqNum, DRV_HB_CHALLENGE) != A_OK) {
2204         AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("Unable to send heart beat challenge\n"));
2205     }
2206
2207
2208     /* Reschedule the timer for the next challenge */
2209     A_TIMEOUT_MS(&ar->arHBChallengeResp.timer, ar->arHBChallengeResp.frequency * 1000, 0);
2210 }
2211
2212 void ar6000_init_profile_info(AR_SOFTC_T *ar)
2213 {
2214     ar->arSsidLen            = 0;
2215     A_MEMZERO(ar->arSsid, sizeof(ar->arSsid));
2216
2217     switch(fwmode) {
2218         case HI_OPTION_FW_MODE_IBSS:
2219             ar->arNetworkType = ar->arNextMode = ADHOC_NETWORK;
2220             break;
2221         case HI_OPTION_FW_MODE_BSS_STA:
2222             ar->arNetworkType = ar->arNextMode = INFRA_NETWORK;
2223             break;
2224         case HI_OPTION_FW_MODE_AP:
2225             ar->arNetworkType = ar->arNextMode = AP_NETWORK;
2226             break;
2227     }
2228
2229     ar->arDot11AuthMode      = OPEN_AUTH;
2230     ar->arAuthMode           = NONE_AUTH;
2231     ar->arPairwiseCrypto     = NONE_CRYPT;
2232     ar->arPairwiseCryptoLen  = 0;
2233     ar->arGroupCrypto        = NONE_CRYPT;
2234     ar->arGroupCryptoLen     = 0;
2235     A_MEMZERO(ar->arWepKeyList, sizeof(ar->arWepKeyList));
2236     A_MEMZERO(ar->arReqBssid, sizeof(ar->arReqBssid));
2237     A_MEMZERO(ar->arBssid, sizeof(ar->arBssid));
2238     ar->arBssChannel = 0;
2239     ar->arConnected = FALSE;
2240 }
2241
2242 static void
2243 ar6000_init_control_info(AR_SOFTC_T *ar)
2244 {
2245     ar->arWmiEnabled         = FALSE;
2246     ar6000_init_profile_info(ar);
2247     ar->arDefTxKeyIndex      = 0;
2248     A_MEMZERO(ar->arWepKeyList, sizeof(ar->arWepKeyList));
2249     ar->arChannelHint        = 0;
2250     ar->arListenIntervalT    = A_DEFAULT_LISTEN_INTERVAL;
2251     ar->arListenIntervalB    = 0;
2252     ar->arVersion.host_ver   = AR6K_SW_VERSION;
2253     ar->arRssi               = 0;
2254     ar->arTxPwr              = 0;
2255     ar->arTxPwrSet           = FALSE;
2256     ar->arSkipScan           = 0;
2257     ar->arBeaconInterval     = 0;
2258     ar->arBitRate            = 0;
2259     ar->arMaxRetries         = 0;
2260     ar->arWmmEnabled         = TRUE;
2261     ar->intra_bss            = 1;
2262     ar->scan_triggered       = 0;
2263     A_MEMZERO(&ar->scParams, sizeof(ar->scParams));
2264     ar->scParams.shortScanRatio = WMI_SHORTSCANRATIO_DEFAULT;
2265     ar->scParams.scanCtrlFlags = DEFAULT_SCAN_CTRL_FLAGS;
2266
2267     /* Initialize the AP mode state info */
2268     {
2269         A_UINT8 ctr;
2270         A_MEMZERO((A_UINT8 *)ar->sta_list, AP_MAX_NUM_STA * sizeof(sta_t));
2271
2272         /* init the Mutexes */
2273         A_MUTEX_INIT(&ar->mcastpsqLock);
2274
2275         /* Init the PS queues */
2276         for (ctr=0; ctr < AP_MAX_NUM_STA ; ctr++) {
2277             A_MUTEX_INIT(&ar->sta_list[ctr].psqLock);
2278             A_NETBUF_QUEUE_INIT(&ar->sta_list[ctr].psq);
2279         }
2280
2281         ar->ap_profile_flag = 0;
2282         A_NETBUF_QUEUE_INIT(&ar->mcastpsq);
2283
2284         A_MEMCPY(ar->ap_country_code, DEF_AP_COUNTRY_CODE, 3);
2285         ar->ap_wmode = DEF_AP_WMODE_G;
2286         ar->ap_dtim_period = DEF_AP_DTIM;
2287         ar->ap_beacon_interval = DEF_BEACON_INTERVAL;
2288     }
2289 }
2290
2291 static int
2292 ar6000_open(struct net_device *dev)
2293 {
2294     unsigned long  flags;
2295     AR_SOFTC_T    *ar = (AR_SOFTC_T *)ar6k_priv(dev);
2296
2297     spin_lock_irqsave(&ar->arLock, flags);
2298
2299 #ifdef ATH6K_CONFIG_CFG80211
2300     if(ar->arWlanState == WLAN_DISABLED) {
2301         ar->arWlanState = WLAN_ENABLED;
2302     }
2303 #endif /* ATH6K_CONFIG_CFG80211 */
2304
2305     if( ar->arConnected || bypasswmi) {
2306         netif_carrier_on(dev);
2307         /* Wake up the queues */
2308         netif_wake_queue(dev);
2309     }
2310     else
2311         netif_carrier_off(dev);
2312
2313     spin_unlock_irqrestore(&ar->arLock, flags);
2314     return 0;
2315 }
2316
2317 static int
2318 ar6000_close(struct net_device *dev)
2319 {
2320 #ifdef ATH6K_CONFIG_CFG80211
2321     AR_SOFTC_T    *ar = (AR_SOFTC_T *)ar6k_priv(dev);
2322 #endif /* ATH6K_CONFIG_CFG80211 */
2323     netif_stop_queue(dev);
2324
2325 #ifdef ATH6K_CONFIG_CFG80211
2326     AR6000_SPIN_LOCK(&ar->arLock, 0);
2327     if (ar->arConnected == TRUE || ar->arConnectPending == TRUE) {
2328         AR6000_SPIN_UNLOCK(&ar->arLock, 0);
2329         wmi_disconnect_cmd(ar->arWmi);
2330     } else {
2331         AR6000_SPIN_UNLOCK(&ar->arLock, 0);
2332     }
2333
2334     if(ar->arWmiReady == TRUE) {
2335         if (wmi_scanparams_cmd(ar->arWmi, 0xFFFF, 0,
2336                                0, 0, 0, 0, 0, 0, 0, 0) != A_OK) {
2337             return -EIO;
2338         }
2339         ar->arWlanState = WLAN_DISABLED;
2340     }
2341 #endif /* ATH6K_CONFIG_CFG80211 */
2342
2343     return 0;
2344 }
2345
2346 /* connect to a service */
2347 static A_STATUS ar6000_connectservice(AR_SOFTC_T               *ar,
2348                                       HTC_SERVICE_CONNECT_REQ  *pConnect,
2349                                       char                     *pDesc)
2350 {
2351     A_STATUS                 status;
2352     HTC_SERVICE_CONNECT_RESP response;
2353
2354     do {
2355
2356         A_MEMZERO(&response,sizeof(response));
2357
2358         status = HTCConnectService(ar->arHtcTarget,
2359                                    pConnect,
2360                                    &response);
2361
2362         if (A_FAILED(status)) {
2363             AR_DEBUG_PRINTF(ATH_DEBUG_ERR,(" Failed to connect to %s service status:%d \n",
2364                               pDesc, status));
2365             break;
2366         }
2367         switch (pConnect->ServiceID) {
2368             case WMI_CONTROL_SVC :
2369                 if (ar->arWmiEnabled) {
2370                         /* set control endpoint for WMI use */
2371                     wmi_set_control_ep(ar->arWmi, response.Endpoint);
2372                 }
2373                     /* save EP for fast lookup */
2374                 ar->arControlEp = response.Endpoint;
2375                 break;
2376             case WMI_DATA_BE_SVC :
2377                 arSetAc2EndpointIDMap(ar, WMM_AC_BE, response.Endpoint);
2378                 break;
2379             case WMI_DATA_BK_SVC :
2380                 arSetAc2EndpointIDMap(ar, WMM_AC_BK, response.Endpoint);
2381                 break;
2382             case WMI_DATA_VI_SVC :
2383                 arSetAc2EndpointIDMap(ar, WMM_AC_VI, response.Endpoint);
2384                  break;
2385            case WMI_DATA_VO_SVC :
2386                 arSetAc2EndpointIDMap(ar, WMM_AC_VO, response.Endpoint);
2387                 break;
2388            default:
2389                 AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("ServiceID not mapped %d\n", pConnect->ServiceID));
2390                 status = A_EINVAL;
2391             break;
2392         }
2393
2394     } while (FALSE);
2395
2396     return status;
2397 }
2398
2399 void ar6000_TxDataCleanup(AR_SOFTC_T *ar)
2400 {
2401         /* flush all the data (non-control) streams
2402          * we only flush packets that are tagged as data, we leave any control packets that
2403          * were in the TX queues alone */
2404     HTCFlushEndpoint(ar->arHtcTarget,
2405                      arAc2EndpointID(ar, WMM_AC_BE),
2406                      AR6K_DATA_PKT_TAG);
2407     HTCFlushEndpoint(ar->arHtcTarget,
2408                      arAc2EndpointID(ar, WMM_AC_BK),
2409                      AR6K_DATA_PKT_TAG);
2410     HTCFlushEndpoint(ar->arHtcTarget,
2411                      arAc2EndpointID(ar, WMM_AC_VI),
2412                      AR6K_DATA_PKT_TAG);
2413     HTCFlushEndpoint(ar->arHtcTarget,
2414                      arAc2EndpointID(ar, WMM_AC_VO),
2415                      AR6K_DATA_PKT_TAG);
2416 }
2417
2418 HTC_ENDPOINT_ID
2419 ar6000_ac2_endpoint_id ( void * devt, A_UINT8 ac)
2420 {
2421     AR_SOFTC_T *ar = (AR_SOFTC_T *) devt;
2422     return(arAc2EndpointID(ar, ac));
2423 }
2424
2425 A_UINT8
2426 ar6000_endpoint_id2_ac(void * devt, HTC_ENDPOINT_ID ep )
2427 {
2428     AR_SOFTC_T *ar = (AR_SOFTC_T *) devt;
2429     return(arEndpoint2Ac(ar, ep ));
2430 }
2431
2432 /* This function does one time initialization for the lifetime of the device */
2433 int ar6000_init(struct net_device *dev)
2434 {
2435     AR_SOFTC_T *ar;
2436     A_STATUS    status;
2437     A_INT32     timeleft;
2438     A_INT16     i;
2439     int         ret = 0;
2440 #if defined(INIT_MODE_DRV_ENABLED) && defined(ENABLE_COEXISTENCE)
2441     WMI_SET_BTCOEX_COLOCATED_BT_DEV_CMD sbcb_cmd;
2442     WMI_SET_BTCOEX_FE_ANT_CMD sbfa_cmd;
2443 #endif /* INIT_MODE_DRV_ENABLED && ENABLE_COEXISTENCE */
2444
2445     if((ar = ar6k_priv(dev)) == NULL)
2446     {
2447         return -EIO;
2448     }
2449
2450     if (wlaninitmode == WLAN_INIT_MODE_USR || wlaninitmode == WLAN_INIT_MODE_DRV) {
2451     
2452         ar6000_update_bdaddr(ar);
2453
2454         if (enablerssicompensation) {
2455             ar6000_copy_cust_data_from_target(ar->arHifDevice, ar->arTargetType);
2456             read_rssi_compensation_param(ar);
2457             for (i=-95; i<=0; i++) {
2458                 rssi_compensation_table[0-i] = rssi_compensation_calc(ar,i);
2459             }
2460         }
2461     }
2462
2463     dev_hold(dev);
2464     rtnl_unlock();
2465
2466     /* Do we need to finish the BMI phase */
2467     if ((wlaninitmode == WLAN_INIT_MODE_USR || wlaninitmode == WLAN_INIT_MODE_DRV) && 
2468         (BMIDone(ar->arHifDevice) != A_OK))
2469     {
2470         ret = -EIO;
2471         goto ar6000_init_done;
2472     }
2473
2474     if (!bypasswmi)
2475     {
2476 #if 0 /* TBDXXX */
2477         if (ar->arVersion.host_ver != ar->arVersion.target_ver) {
2478             A_PRINTF("WARNING: Host version 0x%x does not match Target "
2479                     " version 0x%x!\n",
2480                     ar->arVersion.host_ver, ar->arVersion.target_ver);
2481         }
2482 #endif
2483
2484         /* Indicate that WMI is enabled (although not ready yet) */
2485         ar->arWmiEnabled = TRUE;
2486         if ((ar->arWmi = wmi_init((void *) ar)) == NULL)
2487         {
2488             AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("%s() Failed to initialize WMI.\n", __func__));
2489             ret = -EIO;
2490             goto ar6000_init_done;
2491         }
2492
2493         AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("%s() Got WMI @ 0x%lx.\n", __func__,
2494             (unsigned long) ar->arWmi));
2495     }
2496
2497     do {
2498         HTC_SERVICE_CONNECT_REQ connect;
2499
2500             /* the reason we have to wait for the target here is that the driver layer
2501              * has to init BMI in order to set the host block size,
2502              */
2503         status = HTCWaitTarget(ar->arHtcTarget);
2504
2505         if (A_FAILED(status)) {
2506             break;
2507         }
2508
2509         A_MEMZERO(&connect,sizeof(connect));
2510             /* meta data is unused for now */
2511         connect.pMetaData = NULL;
2512         connect.MetaDataLength = 0;
2513             /* these fields are the same for all service endpoints */
2514         connect.EpCallbacks.pContext = ar;
2515         connect.EpCallbacks.EpTxCompleteMultiple = ar6000_tx_complete;
2516         connect.EpCallbacks.EpRecv = ar6000_rx;
2517         connect.EpCallbacks.EpRecvRefill = ar6000_rx_refill;
2518         connect.EpCallbacks.EpSendFull = ar6000_tx_queue_full;
2519             /* set the max queue depth so that our ar6000_tx_queue_full handler gets called.
2520              * Linux has the peculiarity of not providing flow control between the
2521              * NIC and the network stack. There is no API to indicate that a TX packet
2522              * was sent which could provide some back pressure to the network stack.
2523              * Under linux you would have to wait till the network stack consumed all sk_buffs
2524              * before any back-flow kicked in. Which isn't very friendly.
2525              * So we have to manage this ourselves */
2526         connect.MaxSendQueueDepth = MAX_DEFAULT_SEND_QUEUE_DEPTH;
2527         connect.EpCallbacks.RecvRefillWaterMark = AR6000_MAX_RX_BUFFERS / 4; /* set to 25 % */
2528         if (0 == connect.EpCallbacks.RecvRefillWaterMark) {
2529             connect.EpCallbacks.RecvRefillWaterMark++;
2530         }
2531             /* connect to control service */
2532         connect.ServiceID = WMI_CONTROL_SVC;
2533         status = ar6000_connectservice(ar,
2534                                        &connect,
2535                                        "WMI CONTROL");
2536         if (A_FAILED(status)) {
2537             break;
2538         }
2539
2540         connect.LocalConnectionFlags |= HTC_LOCAL_CONN_FLAGS_ENABLE_SEND_BUNDLE_PADDING;
2541             /* limit the HTC message size on the send path, although we can receive A-MSDU frames of
2542              * 4K, we will only send ethernet-sized (802.3) frames on the send path. */
2543         connect.MaxSendMsgSize = WMI_MAX_TX_DATA_FRAME_LENGTH;
2544
2545             /* to reduce the amount of committed memory for larger A_MSDU frames, use the recv-alloc threshold
2546              * mechanism for larger packets */
2547         connect.EpCallbacks.RecvAllocThreshold = AR6000_BUFFER_SIZE;
2548         connect.EpCallbacks.EpRecvAllocThresh = ar6000_alloc_amsdu_rxbuf;
2549
2550             /* for the remaining data services set the connection flag to reduce dribbling,
2551              * if configured to do so */
2552         if (reduce_credit_dribble) {
2553             connect.ConnectionFlags |= HTC_CONNECT_FLAGS_REDUCE_CREDIT_DRIBBLE;
2554             /* the credit dribble trigger threshold is (reduce_credit_dribble - 1) for a value
2555              * of 0-3 */
2556             connect.ConnectionFlags &= ~HTC_CONNECT_FLAGS_THRESHOLD_LEVEL_MASK;
2557             connect.ConnectionFlags |=
2558                         ((A_UINT16)reduce_credit_dribble - 1) & HTC_CONNECT_FLAGS_THRESHOLD_LEVEL_MASK;
2559         }
2560             /* connect to best-effort service */
2561         connect.ServiceID = WMI_DATA_BE_SVC;
2562
2563         status = ar6000_connectservice(ar,
2564                                        &connect,
2565                                        "WMI DATA BE");
2566         if (A_FAILED(status)) {
2567             break;
2568         }
2569
2570             /* connect to back-ground
2571              * map this to WMI LOW_PRI */
2572         connect.ServiceID = WMI_DATA_BK_SVC;
2573         status = ar6000_connectservice(ar,
2574                                        &connect,
2575                                        "WMI DATA BK");
2576         if (A_FAILED(status)) {
2577             break;
2578         }
2579
2580             /* connect to Video service, map this to
2581              * to HI PRI */
2582         connect.ServiceID = WMI_DATA_VI_SVC;
2583         status = ar6000_connectservice(ar,
2584                                        &connect,
2585                                        "WMI DATA VI");
2586         if (A_FAILED(status)) {
2587             break;
2588         }
2589
2590             /* connect to VO service, this is currently not
2591              * mapped to a WMI priority stream due to historical reasons.
2592              * WMI originally defined 3 priorities over 3 mailboxes
2593              * We can change this when WMI is reworked so that priorities are not
2594              * dependent on mailboxes */
2595         connect.ServiceID = WMI_DATA_VO_SVC;
2596         status = ar6000_connectservice(ar,
2597                                        &connect,
2598                                        "WMI DATA VO");
2599         if (A_FAILED(status)) {
2600             break;
2601         }
2602
2603         A_ASSERT(arAc2EndpointID(ar,WMM_AC_BE) != 0);
2604         A_ASSERT(arAc2EndpointID(ar,WMM_AC_BK) != 0);
2605         A_ASSERT(arAc2EndpointID(ar,WMM_AC_VI) != 0);
2606         A_ASSERT(arAc2EndpointID(ar,WMM_AC_VO) != 0);
2607
2608             /* setup access class priority mappings */
2609         ar->arAcStreamPriMap[WMM_AC_BK] = 0; /* lowest  */
2610         ar->arAcStreamPriMap[WMM_AC_BE] = 1; /*         */
2611         ar->arAcStreamPriMap[WMM_AC_VI] = 2; /*         */
2612         ar->arAcStreamPriMap[WMM_AC_VO] = 3; /* highest */
2613
2614 #ifdef EXPORT_HCI_BRIDGE_INTERFACE
2615         if (setuphci && (NULL != ar6kHciTransCallbacks.setupTransport)) {
2616             HCI_TRANSPORT_MISC_HANDLES hciHandles;
2617
2618             hciHandles.netDevice = ar->arNetDev;
2619             hciHandles.hifDevice = ar->arHifDevice;
2620             hciHandles.htcHandle = ar->arHtcTarget;
2621             status = (A_STATUS)(ar6kHciTransCallbacks.setupTransport(&hciHandles));
2622         }
2623 #else
2624         if (setuphci) {
2625                 /* setup HCI */
2626             status = ar6000_setup_hci(ar);
2627         }
2628 #endif
2629 #ifdef EXPORT_HCI_PAL_INTERFACE
2630         if (setuphcipal && (NULL != ar6kHciPalCallbacks_g.setupTransport))
2631           status = ar6kHciPalCallbacks_g.setupTransport(ar);
2632 #else
2633         if(setuphcipal)
2634           status = ar6k_setup_hci_pal(ar);
2635 #endif
2636
2637     } while (FALSE);
2638
2639     if (A_FAILED(status)) {
2640         ret = -EIO;
2641         goto ar6000_init_done;
2642     }
2643
2644     /*
2645      * give our connected endpoints some buffers
2646      */
2647
2648     ar6000_rx_refill(ar, ar->arControlEp);
2649     ar6000_rx_refill(ar, arAc2EndpointID(ar,WMM_AC_BE));
2650
2651     /*
2652      * We will post the receive buffers only for SPE or endpoint ping testing so we are
2653      * making it conditional on the 'bypasswmi' flag.
2654      */
2655     if (bypasswmi) {
2656         ar6000_rx_refill(ar,arAc2EndpointID(ar,WMM_AC_BK));
2657         ar6000_rx_refill(ar,arAc2EndpointID(ar,WMM_AC_VI));
2658         ar6000_rx_refill(ar,arAc2EndpointID(ar,WMM_AC_VO));
2659     }
2660
2661     /* allocate some buffers that handle larger AMSDU frames */
2662     ar6000_refill_amsdu_rxbufs(ar,AR6000_MAX_AMSDU_RX_BUFFERS);
2663
2664         /* setup credit distribution */
2665     ar6000_setup_credit_dist(ar->arHtcTarget, &ar->arCreditStateInfo);
2666
2667     /* Since cookies are used for HTC transports, they should be */
2668     /* initialized prior to enabling HTC.                        */
2669     ar6000_cookie_init(ar);
2670
2671     /* start HTC */
2672     status = HTCStart(ar->arHtcTarget);
2673
2674     if (status != A_OK) {
2675         if (ar->arWmiEnabled == TRUE) {
2676             wmi_shutdown(ar->arWmi);
2677             ar->arWmiEnabled = FALSE;
2678             ar->arWmi = NULL;
2679         }
2680         ar6000_cookie_cleanup(ar);
2681         ret = -EIO;
2682         goto ar6000_init_done;
2683     }
2684
2685     if (!bypasswmi) {
2686         /* Wait for Wmi event to be ready */
2687         timeleft = wait_event_interruptible_timeout(arEvent,
2688             (ar->arWmiReady == TRUE), wmitimeout * HZ);
2689
2690         if (ar->arVersion.abi_ver != AR6K_ABI_VERSION) {
2691             AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("ABI Version mismatch: Host(0x%x), Target(0x%x)\n", AR6K_ABI_VERSION, ar->arVersion.abi_ver));
2692 #ifndef ATH6K_SKIP_ABI_VERSION_CHECK
2693             ret = -EIO;
2694             goto ar6000_init_done;
2695 #endif /* ATH6K_SKIP_ABI_VERSION_CHECK */
2696         }
2697
2698         if(!timeleft || signal_pending(current))
2699         {
2700             AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("WMI is not ready or wait was interrupted\n"));
2701             ret = -EIO;
2702             goto ar6000_init_done;
2703         }
2704
2705         AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("%s() WMI is ready\n", __func__));
2706
2707         /* Communicate the wmi protocol verision to the target */
2708         if ((ar6000_set_host_app_area(ar)) != A_OK) {
2709             AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("Unable to set the host app area\n"));
2710         }
2711
2712         /* configure the device for rx dot11 header rules 0,0 are the default values
2713          * therefore this command can be skipped if the inputs are 0,FALSE,FALSE.Required
2714          if checksum offload is needed. Set RxMetaVersion to 2*/
2715         if ((wmi_set_rx_frame_format_cmd(ar->arWmi,ar->rxMetaVersion, processDot11Hdr, processDot11Hdr)) != A_OK) {
2716             AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("Unable to set the rx frame format.\n"));
2717         }
2718
2719 #if defined(INIT_MODE_DRV_ENABLED) && defined(ENABLE_COEXISTENCE)
2720         /* Configure the type of BT collocated with WLAN */
2721         A_MEMZERO(&sbcb_cmd, sizeof(WMI_SET_BTCOEX_COLOCATED_BT_DEV_CMD));
2722 #ifdef CONFIG_AR600x_BT_QCOM
2723         sbcb_cmd.btcoexCoLocatedBTdev = 1;
2724 #elif defined(CONFIG_AR600x_BT_CSR)
2725         sbcb_cmd.btcoexCoLocatedBTdev = 2;
2726 #elif defined(CONFIG_AR600x_BT_AR3001)
2727         sbcb_cmd.btcoexCoLocatedBTdev = 3;
2728 #else
2729 #error Unsupported Bluetooth Type
2730 #endif /* Collocated Bluetooth Type */
2731
2732         if ((wmi_set_btcoex_colocated_bt_dev_cmd(ar->arWmi, &sbcb_cmd)) != A_OK)
2733         {
2734             AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("Unable to set collocated BT type\n"));
2735         }
2736
2737         /* Configure the type of BT collocated with WLAN */
2738         A_MEMZERO(&sbfa_cmd, sizeof(WMI_SET_BTCOEX_FE_ANT_CMD));
2739 #ifdef CONFIG_AR600x_DUAL_ANTENNA
2740         sbfa_cmd.btcoexFeAntType = 2;
2741 #elif defined(CONFIG_AR600x_SINGLE_ANTENNA)
2742         sbfa_cmd.btcoexFeAntType = 1;
2743 #else
2744 #error Unsupported Front-End Antenna Configuration
2745 #endif /* AR600x Front-End Antenna Configuration */
2746
2747         if ((wmi_set_btcoex_fe_ant_cmd(ar->arWmi, &sbfa_cmd)) != A_OK) {
2748             AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("Unable to set fornt end antenna configuration\n"));
2749         }
2750 #endif /* INIT_MODE_DRV_ENABLED && ENABLE_COEXISTENCE */
2751     }
2752
2753     ar->arNumDataEndPts = 1;
2754
2755     if (bypasswmi) {
2756             /* for tests like endpoint ping, the MAC address needs to be non-zero otherwise
2757              * the data path through a raw socket is disabled */
2758         dev->dev_addr[0] = 0x00;
2759         dev->dev_addr[1] = 0x01;
2760         dev->dev_addr[2] = 0x02;
2761         dev->dev_addr[3] = 0xAA;
2762         dev->dev_addr[4] = 0xBB;
2763         dev->dev_addr[5] = 0xCC;
2764     }
2765
2766 ar6000_init_done:
2767     rtnl_lock();
2768     dev_put(dev);
2769
2770     return ret;
2771 }
2772
2773
2774 void
2775 ar6000_bitrate_rx(void *devt, A_INT32 rateKbps)
2776 {
2777     AR_SOFTC_T *ar = (AR_SOFTC_T *)devt;
2778
2779     ar->arBitRate = rateKbps;
2780     wake_up(&arEvent);
2781 }
2782
2783 void
2784 ar6000_ratemask_rx(void *devt, A_UINT32 ratemask)
2785 {
2786     AR_SOFTC_T *ar = (AR_SOFTC_T *)devt;
2787
2788     ar->arRateMask = ratemask;
2789     wake_up(&arEvent);
2790 }
2791
2792 void
2793 ar6000_txPwr_rx(void *devt, A_UINT8 txPwr)
2794 {
2795     AR_SOFTC_T *ar = (AR_SOFTC_T *)devt;
2796
2797     ar->arTxPwr = txPwr;
2798     wake_up(&arEvent);
2799 }
2800
2801
2802 void
2803 ar6000_channelList_rx(void *devt, A_INT8 numChan, A_UINT16 *chanList)
2804 {
2805     AR_SOFTC_T *ar = (AR_SOFTC_T *)devt;
2806
2807     A_MEMCPY(ar->arChannelList, chanList, numChan * sizeof (A_UINT16));
2808     ar->arNumChannels = numChan;
2809
2810     wake_up(&arEvent);
2811 }
2812
2813 A_UINT8
2814 ar6000_ibss_map_epid(struct sk_buff *skb, struct net_device *dev, A_UINT32 * mapNo)
2815 {
2816     AR_SOFTC_T      *ar = (AR_SOFTC_T *)ar6k_priv(dev);
2817     A_UINT8         *datap;
2818     ATH_MAC_HDR     *macHdr;
2819     A_UINT32         i, eptMap;
2820
2821     (*mapNo) = 0;
2822     datap = A_NETBUF_DATA(skb);
2823     macHdr = (ATH_MAC_HDR *)(datap + sizeof(WMI_DATA_HDR));
2824     if (IEEE80211_IS_MULTICAST(macHdr->dstMac)) {
2825         return ENDPOINT_2;
2826     }
2827
2828     eptMap = -1;
2829     for (i = 0; i < ar->arNodeNum; i ++) {
2830         if (IEEE80211_ADDR_EQ(macHdr->dstMac, ar->arNodeMap[i].macAddress)) {
2831             (*mapNo) = i + 1;
2832             ar->arNodeMap[i].txPending ++;
2833             return ar->arNodeMap[i].epId;
2834         }
2835
2836         if ((eptMap == -1) && !ar->arNodeMap[i].txPending) {
2837             eptMap = i;
2838         }
2839     }
2840
2841     if (eptMap == -1) {
2842         eptMap = ar->arNodeNum;
2843         ar->arNodeNum ++;
2844         A_ASSERT(ar->arNodeNum <= MAX_NODE_NUM);
2845     }
2846
2847     A_MEMCPY(ar->arNodeMap[eptMap].macAddress, macHdr->dstMac, IEEE80211_ADDR_LEN);
2848
2849     for (i = ENDPOINT_2; i <= ENDPOINT_5; i ++) {
2850         if (!ar->arTxPending[i]) {
2851             ar->arNodeMap[eptMap].epId = i;
2852             break;
2853         }
2854         // No free endpoint is available, start redistribution on the inuse endpoints.
2855         if (i == ENDPOINT_5) {
2856             ar->arNodeMap[eptMap].epId = ar->arNexEpId;
2857             ar->arNexEpId ++;
2858             if (ar->arNexEpId > ENDPOINT_5) {
2859                 ar->arNexEpId = ENDPOINT_2;
2860             }
2861         }
2862     }
2863
2864     (*mapNo) = eptMap + 1;
2865     ar->arNodeMap[eptMap].txPending ++;
2866
2867     return ar->arNodeMap[eptMap].epId;
2868 }
2869
2870 #ifdef DEBUG
2871 static void ar6000_dump_skb(struct sk_buff *skb)
2872 {
2873    u_char *ch;
2874    for (ch = A_NETBUF_DATA(skb);
2875         (unsigned long)ch < ((unsigned long)A_NETBUF_DATA(skb) +
2876         A_NETBUF_LEN(skb)); ch++)
2877     {
2878          AR_DEBUG_PRINTF(ATH_DEBUG_WARN,("%2.2x ", *ch));
2879     }
2880     AR_DEBUG_PRINTF(ATH_DEBUG_WARN,("\n"));
2881 }
2882 #endif
2883
2884 #ifdef HTC_TEST_SEND_PKTS
2885 static void DoHTCSendPktsTest(AR_SOFTC_T *ar, int MapNo, HTC_ENDPOINT_ID eid, struct sk_buff *skb);
2886 #endif
2887
2888 static int
2889 ar6000_data_tx(struct sk_buff *skb, struct net_device *dev)
2890 {
2891 #define AC_NOT_MAPPED   99
2892     AR_SOFTC_T        *ar = (AR_SOFTC_T *)ar6k_priv(dev);
2893     A_UINT8            ac = AC_NOT_MAPPED;
2894     HTC_ENDPOINT_ID    eid = ENDPOINT_UNUSED;
2895     A_UINT32          mapNo = 0;
2896     int               len;
2897     struct ar_cookie *cookie;
2898     A_BOOL            checkAdHocPsMapping = FALSE,bMoreData = FALSE;
2899     HTC_TX_TAG        htc_tag = AR6K_DATA_PKT_TAG;
2900     A_UINT8           dot11Hdr = processDot11Hdr;
2901 #ifdef CONFIG_PM
2902     if (ar->arWowState != WLAN_WOW_STATE_NONE) {
2903         A_NETBUF_FREE(skb);
2904         return 0;
2905     }
2906 #endif /* CONFIG_PM */
2907
2908     AR_DEBUG_PRINTF(ATH_DEBUG_WLAN_TX,("ar6000_data_tx start - skb=0x%lx, data=0x%lx, len=0x%x\n",
2909                      (unsigned long)skb, (unsigned long)A_NETBUF_DATA(skb),
2910                      A_NETBUF_LEN(skb)));
2911
2912     /* If target is not associated */
2913     if( (!ar->arConnected && !bypasswmi)
2914 #ifdef CONFIG_HOST_TCMD_SUPPORT
2915      /* TCMD doesnt support any data, free the buf and return */
2916     || (ar->arTargetMode == AR6000_TCMD_MODE)
2917 #endif
2918                                             ) {
2919         A_NETBUF_FREE(skb);
2920         return 0;
2921     }
2922
2923     do {
2924
2925         if (ar->arWmiReady == FALSE && bypasswmi == 0) {
2926             break;
2927         }
2928
2929 #ifdef BLOCK_TX_PATH_FLAG
2930         if (blocktx) {
2931             break;
2932         }
2933 #endif /* BLOCK_TX_PATH_FLAG */
2934
2935         /* AP mode Power save processing */
2936         /* If the dst STA is in sleep state, queue the pkt in its PS queue */
2937
2938         if (ar->arNetworkType == AP_NETWORK) {
2939             ATH_MAC_HDR *datap = (ATH_MAC_HDR *)A_NETBUF_DATA(skb);
2940             sta_t *conn = NULL;
2941
2942             /* If the dstMac is a Multicast address & atleast one of the
2943              * associated STA is in PS mode, then queue the pkt to the
2944              * mcastq
2945              */
2946             if (IEEE80211_IS_MULTICAST(datap->dstMac)) {
2947                 A_UINT8 ctr=0;
2948                 A_BOOL qMcast=FALSE;
2949
2950
2951                 for (ctr=0; ctr<AP_MAX_NUM_STA; ctr++) {
2952                     if (STA_IS_PWR_SLEEP((&ar->sta_list[ctr]))) {
2953                         qMcast = TRUE;
2954                     }
2955                 }
2956                 if(qMcast) {
2957
2958                     /* If this transmit is not because of a Dtim Expiry q it */
2959                     if (ar->DTIMExpired == FALSE) {
2960                         A_BOOL isMcastqEmpty = FALSE;
2961
2962                         A_MUTEX_LOCK(&ar->mcastpsqLock);
2963                         isMcastqEmpty = A_NETBUF_QUEUE_EMPTY(&ar->mcastpsq);
2964                         A_NETBUF_ENQUEUE(&ar->mcastpsq, skb);
2965                         A_MUTEX_UNLOCK(&ar->mcastpsqLock);
2966
2967                         /* If this is the first Mcast pkt getting queued
2968                          * indicate to the target to set the BitmapControl LSB
2969                          * of the TIM IE.
2970                          */
2971                         if (isMcastqEmpty) {
2972                              wmi_set_pvb_cmd(ar->arWmi, MCAST_AID, 1);
2973                         }
2974                         return 0;
2975                     } else {
2976                      /* This transmit is because of Dtim expiry. Determine if
2977                       * MoreData bit has to be set.
2978                       */
2979                          A_MUTEX_LOCK(&ar->mcastpsqLock);
2980                          if(!A_NETBUF_QUEUE_EMPTY(&ar->mcastpsq)) {
2981                              bMoreData = TRUE;
2982                          }
2983                          A_MUTEX_UNLOCK(&ar->mcastpsqLock);
2984                     }
2985                 }
2986             } else {
2987                 conn = ieee80211_find_conn(ar, datap->dstMac);
2988                 if (conn) {
2989                     if (STA_IS_PWR_SLEEP(conn)) {
2990                         /* If this transmit is not because of a PsPoll q it*/
2991                         if (!STA_IS_PS_POLLED(conn)) {
2992                             A_BOOL isPsqEmpty = FALSE;
2993                             /* Queue the frames if the STA is sleeping */
2994                             A_MUTEX_LOCK(&conn->psqLock);
2995                             isPsqEmpty = A_NETBUF_QUEUE_EMPTY(&conn->psq);
2996                             A_NETBUF_ENQUEUE(&conn->psq, skb);
2997                             A_MUTEX_UNLOCK(&conn->psqLock);
2998
2999                             /* If this is the first pkt getting queued
3000                              * for this STA, update the PVB for this STA
3001                              */
3002                             if (isPsqEmpty) {
3003                                 wmi_set_pvb_cmd(ar->arWmi, conn->aid, 1);
3004                             }
3005
3006                             return 0;
3007                          } else {
3008                          /* This tx is because of a PsPoll. Determine if
3009                           * MoreData bit has to be set
3010                           */
3011                              A_MUTEX_LOCK(&conn->psqLock);
3012                              if (!A_NETBUF_QUEUE_EMPTY(&conn->psq)) {
3013                                  bMoreData = TRUE;
3014                              }
3015                              A_MUTEX_UNLOCK(&conn->psqLock);
3016                          }
3017                     }
3018                 } else {
3019
3020                     /* non existent STA. drop the frame */
3021                     A_NETBUF_FREE(skb);
3022                     return 0;
3023                 }
3024             }
3025         }
3026
3027         if (ar->arWmiEnabled) {
3028 #ifdef CONFIG_CHECKSUM_OFFLOAD
3029         A_UINT8 csumStart=0;
3030         A_UINT8 csumDest=0;
3031         A_UINT8 csum=skb->ip_summed;
3032         if(csumOffload && (csum==CHECKSUM_PARTIAL)){
3033             csumStart=skb->csum_start-(skb->network_header-skb->head)+sizeof(ATH_LLC_SNAP_HDR);
3034             csumDest=skb->csum_offset+csumStart;
3035         }
3036 #endif
3037             if (A_NETBUF_HEADROOM(skb) < dev->hard_header_len - LINUX_HACK_FUDGE_FACTOR) {
3038                 struct sk_buff  *newbuf;
3039
3040                 /*
3041                  * We really should have gotten enough headroom but sometimes
3042                  * we still get packets with not enough headroom.  Copy the packet.
3043                  */
3044                 len = A_NETBUF_LEN(skb);
3045                 newbuf = A_NETBUF_ALLOC(len);
3046                 if (newbuf == NULL) {
3047                     break;
3048                 }
3049                 A_NETBUF_PUT(newbuf, len);
3050                 A_MEMCPY(A_NETBUF_DATA(newbuf), A_NETBUF_DATA(skb), len);
3051                 A_NETBUF_FREE(skb);
3052                 skb = newbuf;
3053                 /* fall through and assemble header */
3054             }
3055
3056             if (dot11Hdr) {
3057                 if (wmi_dot11_hdr_add(ar->arWmi,skb,ar->arNetworkType) != A_OK) {
3058                     AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("ar6000_data_tx-wmi_dot11_hdr_add failed\n"));
3059                     break;
3060                 }
3061             } else {
3062                 if (wmi_dix_2_dot3(ar->arWmi, skb) != A_OK) {
3063                     AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("ar6000_data_tx - wmi_dix_2_dot3 failed\n"));
3064                     break;
3065                 }
3066             }
3067 #ifdef CONFIG_CHECKSUM_OFFLOAD
3068             if(csumOffload && (csum ==CHECKSUM_PARTIAL)){
3069                 WMI_TX_META_V2  metaV2;
3070                 metaV2.csumStart =csumStart;
3071                 metaV2.csumDest = csumDest;
3072                 metaV2.csumFlags = 0x1;/*instruct target to calculate checksum*/
3073                 if (wmi_data_hdr_add(ar->arWmi, skb, DATA_MSGTYPE, bMoreData, dot11Hdr,
3074                                         WMI_META_VERSION_2,&metaV2) != A_OK) {
3075                     AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("ar6000_data_tx - wmi_data_hdr_add failed\n"));
3076                     break;
3077                 }
3078
3079             }
3080             else
3081 #endif
3082             {
3083                 if (wmi_data_hdr_add(ar->arWmi, skb, DATA_MSGTYPE, bMoreData, dot11Hdr,0,NULL) != A_OK) {
3084                     AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("ar6000_data_tx - wmi_data_hdr_add failed\n"));
3085                     break;
3086                 }
3087             }
3088
3089
3090             if ((ar->arNetworkType == ADHOC_NETWORK) &&
3091                 ar->arIbssPsEnable && ar->arConnected) {
3092                     /* flag to check adhoc mapping once we take the lock below: */
3093                 checkAdHocPsMapping = TRUE;
3094
3095             } else {
3096                     /* get the stream mapping */
3097                 ac  =  wmi_implicit_create_pstream(ar->arWmi, skb, 0, ar->arWmmEnabled);
3098             }
3099
3100         } else {
3101             EPPING_HEADER    *eppingHdr;
3102
3103             eppingHdr = A_NETBUF_DATA(skb);
3104
3105             if (IS_EPPING_PACKET(eppingHdr)) {
3106                     /* the stream ID is mapped to an access class */
3107                 ac = eppingHdr->StreamNo_h;
3108                     /* some EPPING packets cannot be dropped no matter what access class it was
3109                      * sent on.  We can change the packet tag to guarantee it will not get dropped */
3110                 if (IS_EPING_PACKET_NO_DROP(eppingHdr)) {
3111                     htc_tag = AR6K_CONTROL_PKT_TAG;
3112                 }
3113
3114                 if (ac == HCI_TRANSPORT_STREAM_NUM) {
3115                         /* pass this to HCI */
3116 #ifndef EXPORT_HCI_BRIDGE_INTERFACE
3117                     if (A_SUCCESS(hci_test_send(ar,skb))) {
3118                         return 0;
3119                     }
3120 #endif
3121                         /* set AC to discard this skb */
3122                     ac = AC_NOT_MAPPED;
3123                 } else {
3124                     /* a quirk of linux, the payload of the frame is 32-bit aligned and thus the addition
3125                      * of the HTC header will mis-align the start of the HTC frame, so we add some
3126                      * padding which will be stripped off in the target */
3127                     if (EPPING_ALIGNMENT_PAD > 0) {
3128                         A_NETBUF_PUSH(skb, EPPING_ALIGNMENT_PAD);
3129                     }
3130                 }
3131
3132             } else {
3133                     /* not a ping packet, drop it */
3134                 ac = AC_NOT_MAPPED;
3135             }
3136         }
3137
3138     } while (FALSE);
3139
3140         /* did we succeed ? */
3141     if ((ac == AC_NOT_MAPPED) && !checkAdHocPsMapping) {
3142             /* cleanup and exit */
3143         A_NETBUF_FREE(skb);
3144         AR6000_STAT_INC(ar, tx_dropped);
3145         AR6000_STAT_INC(ar, tx_aborted_errors);
3146         return 0;
3147     }
3148
3149     cookie = NULL;
3150
3151         /* take the lock to protect driver data */
3152     AR6000_SPIN_LOCK(&ar->arLock, 0);
3153
3154     do {
3155
3156         if (checkAdHocPsMapping) {
3157             eid = ar6000_ibss_map_epid(skb, dev, &mapNo);
3158         }else {
3159             eid = arAc2EndpointID (ar, ac);
3160         }
3161             /* validate that the endpoint is connected */
3162         if (eid == 0 || eid == ENDPOINT_UNUSED ) {
3163             AR_DEBUG_PRINTF(ATH_DEBUG_ERR,(" eid %d is NOT mapped!\n", eid));
3164             break;
3165         }
3166             /* allocate resource for this packet */
3167         cookie = ar6000_alloc_cookie(ar);
3168
3169         if (cookie != NULL) {
3170                 /* update counts while the lock is held */
3171             ar->arTxPending[eid]++;
3172             ar->arTotalTxDataPending++;
3173         }
3174
3175     } while (FALSE);
3176
3177     AR6000_SPIN_UNLOCK(&ar->arLock, 0);
3178
3179     if (cookie != NULL) {
3180         cookie->arc_bp[0] = (unsigned long)skb;
3181         cookie->arc_bp[1] = mapNo;
3182         SET_HTC_PACKET_INFO_TX(&cookie->HtcPkt,
3183                                cookie,
3184                                A_NETBUF_DATA(skb),
3185                                A_NETBUF_LEN(skb),
3186                                eid,
3187                                htc_tag);
3188
3189 #ifdef DEBUG
3190         if (debugdriver >= 3) {
3191             ar6000_dump_skb(skb);
3192         }
3193 #endif
3194 #ifdef HTC_TEST_SEND_PKTS
3195         DoHTCSendPktsTest(ar,mapNo,eid,skb);
3196 #endif
3197             /* HTC interface is asynchronous, if this fails, cleanup will happen in
3198              * the ar6000_tx_complete callback */
3199         HTCSendPkt(ar->arHtcTarget, &cookie->HtcPkt);
3200     } else {
3201             /* no packet to send, cleanup */
3202         A_NETBUF_FREE(skb);
3203         AR6000_STAT_INC(ar, tx_dropped);
3204         AR6000_STAT_INC(ar, tx_aborted_errors);
3205     }
3206
3207     return 0;
3208 }
3209
3210 int
3211 ar6000_acl_data_tx(struct sk_buff *skb, struct net_device *dev)
3212 {
3213     AR_SOFTC_T        *ar = (AR_SOFTC_T *)ar6k_priv(dev);
3214     struct ar_cookie *cookie;
3215     HTC_ENDPOINT_ID    eid = ENDPOINT_UNUSED;
3216
3217     cookie = NULL;
3218     AR6000_SPIN_LOCK(&ar->arLock, 0);
3219
3220         /* For now we send ACL on BE endpoint: We can also have a dedicated EP */
3221         eid = arAc2EndpointID (ar, 0);
3222         /* allocate resource for this packet */
3223         cookie = ar6000_alloc_cookie(ar);
3224
3225         if (cookie != NULL) {
3226             /* update counts while the lock is held */
3227             ar->arTxPending[eid]++;
3228             ar->arTotalTxDataPending++;
3229         }
3230
3231
3232     AR6000_SPIN_UNLOCK(&ar->arLock, 0);
3233
3234         if (cookie != NULL) {
3235             cookie->arc_bp[0] = (unsigned long)skb;
3236             cookie->arc_bp[1] = 0;
3237             SET_HTC_PACKET_INFO_TX(&cookie->HtcPkt,
3238                             cookie,
3239                             A_NETBUF_DATA(skb),
3240                             A_NETBUF_LEN(skb),
3241                             eid,
3242                             AR6K_DATA_PKT_TAG);
3243
3244             /* HTC interface is asynchronous, if this fails, cleanup will happen in
3245              * the ar6000_tx_complete callback */
3246             HTCSendPkt(ar->arHtcTarget, &cookie->HtcPkt);
3247         } else {
3248             /* no packet to send, cleanup */
3249             A_NETBUF_FREE(skb);
3250             AR6000_STAT_INC(ar, tx_dropped);
3251             AR6000_STAT_INC(ar, tx_aborted_errors);
3252         }
3253     return 0;
3254 }
3255
3256
3257 #ifdef ADAPTIVE_POWER_THROUGHPUT_CONTROL
3258 static void
3259 tvsub(register struct timeval *out, register struct timeval *in)
3260 {
3261     if((out->tv_usec -= in->tv_usec) < 0) {
3262         out->tv_sec--;
3263         out->tv_usec += 1000000;
3264     }
3265     out->tv_sec -= in->tv_sec;
3266 }
3267
3268 void
3269 applyAPTCHeuristics(AR_SOFTC_T *ar)
3270 {
3271     A_UINT32 duration;
3272     A_UINT32 numbytes;
3273     A_UINT32 throughput;
3274     struct timeval ts;
3275     A_STATUS status;
3276
3277     AR6000_SPIN_LOCK(&ar->arLock, 0);
3278
3279     if ((enableAPTCHeuristics) && (!aptcTR.timerScheduled)) {
3280         do_gettimeofday(&ts);
3281         tvsub(&ts, &aptcTR.samplingTS);
3282         duration = ts.tv_sec * 1000 + ts.tv_usec / 1000; /* ms */
3283         numbytes = aptcTR.bytesTransmitted + aptcTR.bytesReceived;
3284
3285         if (duration > APTC_TRAFFIC_SAMPLING_INTERVAL) {
3286             /* Initialize the time stamp and byte count */
3287             aptcTR.bytesTransmitted = aptcTR.bytesReceived = 0;
3288             do_gettimeofday(&aptcTR.samplingTS);
3289
3290             /* Calculate and decide based on throughput thresholds */
3291             throughput = ((numbytes * 8) / duration);
3292             if (throughput > APTC_UPPER_THROUGHPUT_THRESHOLD) {
3293                 /* Disable Sleep and schedule a timer */
3294                 A_ASSERT(ar->arWmiReady == TRUE);
3295                 AR6000_SPIN_UNLOCK(&ar->arLock, 0);
3296                 status = wmi_powermode_cmd(ar->arWmi, MAX_PERF_POWER);
3297                 AR6000_SPIN_LOCK(&ar->arLock, 0);
3298                 A_TIMEOUT_MS(&aptcTimer, APTC_TRAFFIC_SAMPLING_INTERVAL, 0);
3299                 aptcTR.timerScheduled = TRUE;
3300             }
3301         }
3302     }
3303
3304     AR6000_SPIN_UNLOCK(&ar->arLock, 0);
3305 }
3306 #endif /* ADAPTIVE_POWER_THROUGHPUT_CONTROL */
3307
3308 static HTC_SEND_FULL_ACTION ar6000_tx_queue_full(void *Context, HTC_PACKET *pPacket)
3309 {
3310     AR_SOFTC_T     *ar = (AR_SOFTC_T *)Context;
3311     HTC_SEND_FULL_ACTION    action = HTC_SEND_FULL_KEEP;
3312     A_BOOL                  stopNet = FALSE;
3313     HTC_ENDPOINT_ID         Endpoint = HTC_GET_ENDPOINT_FROM_PKT(pPacket);
3314
3315     do {
3316
3317         if (bypasswmi) {
3318             int accessClass;
3319
3320             if (HTC_GET_TAG_FROM_PKT(pPacket) == AR6K_CONTROL_PKT_TAG) {
3321                     /* don't drop special control packets */
3322                 break;
3323             }
3324
3325             accessClass = arEndpoint2Ac(ar,Endpoint);
3326                 /* for endpoint ping testing drop Best Effort and Background */
3327             if ((accessClass == WMM_AC_BE) || (accessClass == WMM_AC_BK)) {
3328                 action = HTC_SEND_FULL_DROP;
3329                 stopNet = FALSE;
3330             } else {
3331                     /* keep but stop the netqueues */
3332                 stopNet = TRUE;
3333             }
3334             break;
3335         }
3336
3337         if (Endpoint == ar->arControlEp) {
3338                 /* under normal WMI if this is getting full, then something is running rampant
3339                  * the host should not be exhausting the WMI queue with too many commands
3340                  * the only exception to this is during testing using endpointping */
3341             AR6000_SPIN_LOCK(&ar->arLock, 0);
3342                 /* set flag to handle subsequent messages */
3343             ar->arWMIControlEpFull = TRUE;
3344             AR6000_SPIN_UNLOCK(&ar->arLock, 0);
3345             AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("WMI Control Endpoint is FULL!!! \n"));
3346                 /* no need to stop the network */
3347             stopNet = FALSE;
3348             break;
3349         }
3350
3351         /* if we get here, we are dealing with data endpoints getting full */
3352
3353         if (HTC_GET_TAG_FROM_PKT(pPacket) == AR6K_CONTROL_PKT_TAG) {
3354             /* don't drop control packets issued on ANY data endpoint */
3355             break;
3356         }
3357
3358         if (ar->arNetworkType == ADHOC_NETWORK) {
3359             /* in adhoc mode, we cannot differentiate traffic priorities so there is no need to
3360              * continue, however we should stop the network */
3361             stopNet = TRUE;
3362             break;
3363         }
3364         /* the last MAX_HI_COOKIE_NUM "batch" of cookies are reserved for the highest
3365          * active stream */
3366         if (ar->arAcStreamPriMap[arEndpoint2Ac(ar,Endpoint)] < ar->arHiAcStreamActivePri &&
3367             ar->arCookieCount <= MAX_HI_COOKIE_NUM) {
3368                 /* this stream's priority is less than the highest active priority, we
3369                  * give preference to the highest priority stream by directing
3370                  * HTC to drop the packet that overflowed */
3371             action = HTC_SEND_FULL_DROP;
3372                 /* since we are dropping packets, no need to stop the network */
3373             stopNet = FALSE;
3374             break;
3375         }
3376
3377     } while (FALSE);
3378
3379     if (stopNet) {
3380         AR6000_SPIN_LOCK(&ar->arLock, 0);
3381         ar->arNetQueueStopped = TRUE;
3382         AR6000_SPIN_UNLOCK(&ar->arLock, 0);
3383         /* one of the data endpoints queues is getting full..need to stop network stack
3384          * the queue will resume in ar6000_tx_complete() */
3385         netif_stop_queue(ar->arNetDev);
3386     }
3387
3388     return action;
3389 }
3390
3391
3392 static void
3393 ar6000_tx_complete(void *Context, HTC_PACKET_QUEUE *pPacketQueue)
3394 {
3395     AR_SOFTC_T     *ar = (AR_SOFTC_T *)Context;
3396     A_UINT32        mapNo = 0;
3397     A_STATUS        status;
3398     struct ar_cookie * ar_cookie;
3399     HTC_ENDPOINT_ID   eid;
3400     A_BOOL          wakeEvent = FALSE;
3401     struct sk_buff_head  skb_queue;
3402     HTC_PACKET      *pPacket;
3403     struct sk_buff  *pktSkb;
3404     A_BOOL          flushing = FALSE;
3405
3406     skb_queue_head_init(&skb_queue);
3407
3408         /* lock the driver as we update internal state */
3409     AR6000_SPIN_LOCK(&ar->arLock, 0);
3410
3411         /* reap completed packets */
3412     while (!HTC_QUEUE_EMPTY(pPacketQueue)) {
3413
3414         pPacket = HTC_PACKET_DEQUEUE(pPacketQueue);
3415
3416         ar_cookie = (struct ar_cookie *)pPacket->pPktContext;
3417         A_ASSERT(ar_cookie);
3418
3419         status = pPacket->Status;
3420         pktSkb = (struct sk_buff *)ar_cookie->arc_bp[0];
3421         eid = pPacket->Endpoint;
3422         mapNo = ar_cookie->arc_bp[1];
3423
3424         A_ASSERT(pktSkb);
3425         A_ASSERT(pPacket->pBuffer == A_NETBUF_DATA(pktSkb));
3426
3427             /* add this to the list, use faster non-lock API */
3428         __skb_queue_tail(&skb_queue,pktSkb);
3429
3430         if (A_SUCCESS(status)) {
3431             A_ASSERT(pPacket->ActualLength == A_NETBUF_LEN(pktSkb));
3432         }
3433
3434         AR_DEBUG_PRINTF(ATH_DEBUG_WLAN_TX,("ar6000_tx_complete skb=0x%lx data=0x%lx len=0x%x eid=%d ",
3435                          (unsigned long)pktSkb, (unsigned long)pPacket->pBuffer,
3436                          pPacket->ActualLength,
3437                          eid));
3438
3439         ar->arTxPending[eid]--;
3440
3441         if ((eid  != ar->arControlEp) || bypasswmi) {
3442             ar->arTotalTxDataPending--;
3443         }
3444
3445         if (eid == ar->arControlEp)
3446         {
3447             if (ar->arWMIControlEpFull) {
3448                     /* since this packet completed, the WMI EP is no longer full */
3449                 ar->arWMIControlEpFull = FALSE;
3450             }
3451
3452             if (ar->arTxPending[eid] == 0) {
3453                 wakeEvent = TRUE;
3454             }
3455         }
3456
3457         if (A_FAILED(status)) {
3458             if (status == A_ECANCELED) {
3459                     /* a packet was flushed  */
3460                 flushing = TRUE;
3461             }
3462             AR6000_STAT_INC(ar, tx_errors);
3463             if (status != A_NO_RESOURCE) {
3464                 AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("%s() -TX ERROR, status: 0x%x\n", __func__,
3465                             status));
3466             }
3467         } else {
3468             AR_DEBUG_PRINTF(ATH_DEBUG_WLAN_TX,("OK\n"));
3469             flushing = FALSE;
3470             AR6000_STAT_INC(ar, tx_packets);
3471             ar->arNetStats.tx_bytes += A_NETBUF_LEN(pktSkb);
3472 #ifdef ADAPTIVE_POWER_THROUGHPUT_CONTROL
3473             aptcTR.bytesTransmitted += a_netbuf_to_len(pktSkb);
3474             applyAPTCHeuristics(ar);
3475 #endif /* ADAPTIVE_POWER_THROUGHPUT_CONTROL */
3476         }
3477
3478         // TODO this needs to be looked at
3479         if ((ar->arNetworkType == ADHOC_NETWORK) && ar->arIbssPsEnable
3480             && (eid != ar->arControlEp) && mapNo)
3481         {
3482             mapNo --;
3483             ar->arNodeMap[mapNo].txPending --;
3484
3485             if (!ar->arNodeMap[mapNo].txPending && (mapNo == (ar->arNodeNum - 1))) {
3486                 A_UINT32 i;
3487                 for (i = ar->arNodeNum; i > 0; i --) {
3488                     if (!ar->arNodeMap[i - 1].txPending) {
3489                         A_MEMZERO(&ar->arNodeMap[i - 1], sizeof(struct ar_node_mapping));
3490                         ar->arNodeNum --;
3491                     } else {
3492                         break;
3493                     }
3494                 }
3495             }
3496         }
3497
3498         ar6000_free_cookie(ar, ar_cookie);
3499
3500         if (ar->arNetQueueStopped) {
3501             ar->arNetQueueStopped = FALSE;
3502         }
3503     }
3504
3505     AR6000_SPIN_UNLOCK(&ar->arLock, 0);
3506
3507     /* lock is released, we can freely call other kernel APIs */
3508
3509         /* free all skbs in our local list */
3510     while (!skb_queue_empty(&skb_queue)) {
3511             /* use non-lock version */
3512         pktSkb = __skb_dequeue(&skb_queue);
3513         A_NETBUF_FREE(pktSkb);
3514     }
3515
3516     if ((ar->arConnected == TRUE) || (bypasswmi)) {
3517         if (!flushing) {
3518                 /* don't wake the queue if we are flushing, other wise it will just
3519                  * keep queueing packets, which will keep failing */
3520             netif_wake_queue(ar->arNetDev);
3521         }
3522     }
3523
3524     if (wakeEvent) {
3525         wake_up(&arEvent);
3526     }
3527
3528 }
3529
3530 sta_t *
3531 ieee80211_find_conn(AR_SOFTC_T *ar, A_UINT8 *node_addr)
3532 {
3533     sta_t *conn = NULL;
3534     A_UINT8 i, max_conn;
3535
3536     switch(ar->arNetworkType) {
3537         case AP_NETWORK:
3538             max_conn = AP_MAX_NUM_STA;
3539             break;
3540         default:
3541             max_conn=0;
3542             break;
3543     }
3544
3545     for (i = 0; i < max_conn; i++) {
3546         if (IEEE80211_ADDR_EQ(node_addr, ar->sta_list[i].mac)) {
3547             conn = &ar->sta_list[i];
3548             break;
3549         }
3550     }
3551
3552     return conn;
3553 }
3554
3555 sta_t *ieee80211_find_conn_for_aid(AR_SOFTC_T *ar, A_UINT8 aid)
3556 {
3557     sta_t *conn = NULL;
3558     A_UINT8 ctr;
3559
3560     for (ctr = 0; ctr < AP_MAX_NUM_STA; ctr++) {
3561         if (ar->sta_list[ctr].aid == aid) {
3562             conn = &ar->sta_list[ctr];
3563             break;
3564         }
3565     }
3566     return conn;
3567 }
3568
3569 /*
3570  * Receive event handler.  This is called by HTC when a packet is received
3571  */
3572 int pktcount;
3573 static void
3574 ar6000_rx(void *Context, HTC_PACKET *pPacket)
3575 {
3576     AR_SOFTC_T *ar = (AR_SOFTC_T *)Context;
3577     struct sk_buff *skb = (struct sk_buff *)pPacket->pPktContext;
3578     int minHdrLen;
3579     A_UINT8 containsDot11Hdr = 0;
3580     A_STATUS        status = pPacket->Status;
3581     HTC_ENDPOINT_ID   ept = pPacket->Endpoint;
3582
3583     A_ASSERT((status != A_OK) ||
3584              (pPacket->pBuffer == (A_NETBUF_DATA(skb) + HTC_HEADER_LEN)));
3585
3586     AR_DEBUG_PRINTF(ATH_DEBUG_WLAN_RX,("ar6000_rx ar=0x%lx eid=%d, skb=0x%lx, data=0x%lx, len=0x%x status:%d",
3587                     (unsigned long)ar, ept, (unsigned long)skb, (unsigned long)pPacket->pBuffer,
3588                     pPacket->ActualLength, status));
3589     if (status != A_OK) {
3590         if (status != A_ECANCELED) {
3591             AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("RX ERR (%d) \n",status));
3592         }
3593     }
3594
3595         /* take lock to protect buffer counts
3596          * and adaptive power throughput state */
3597     AR6000_SPIN_LOCK(&ar->arLock, 0);
3598
3599     if (A_SUCCESS(status)) {
3600         AR6000_STAT_INC(ar, rx_packets);
3601         ar->arNetStats.rx_bytes += pPacket->ActualLength;
3602 #ifdef ADAPTIVE_POWER_THROUGHPUT_CONTROL
3603         aptcTR.bytesReceived += a_netbuf_to_len(skb);
3604         applyAPTCHeuristics(ar);
3605 #endif /* ADAPTIVE_POWER_THROUGHPUT_CONTROL */
3606
3607         A_NETBUF_PUT(skb, pPacket->ActualLength +  HTC_HEADER_LEN);
3608         A_NETBUF_PULL(skb, HTC_HEADER_LEN);
3609
3610 #ifdef DEBUG
3611         if (debugdriver >= 2) {
3612             ar6000_dump_skb(skb);
3613         }
3614 #endif /* DEBUG */
3615     }
3616
3617     AR6000_SPIN_UNLOCK(&ar->arLock, 0);
3618
3619     skb->dev = ar->arNetDev;
3620     if (status != A_OK) {
3621         AR6000_STAT_INC(ar, rx_errors);
3622         A_NETBUF_FREE(skb);
3623     } else if (ar->arWmiEnabled == TRUE) {
3624         if (ept == ar->arControlEp) {
3625            /*
3626             * this is a wmi control msg
3627             */
3628 #ifdef CONFIG_PM 
3629             ar6000_check_wow_status(ar, skb, TRUE);
3630 #endif /* CONFIG_PM */
3631             wmi_control_rx(ar->arWmi, skb);
3632         } else {
3633                 WMI_DATA_HDR *dhdr = (WMI_DATA_HDR *)A_NETBUF_DATA(skb);
3634                 A_UINT8 is_amsdu, tid, is_acl_data_frame;
3635                 is_acl_data_frame = WMI_DATA_HDR_GET_DATA_TYPE(dhdr) == WMI_DATA_HDR_DATA_TYPE_ACL;
3636 #ifdef CONFIG_PM 
3637                 ar6000_check_wow_status(ar, NULL, FALSE);
3638 #endif /* CONFIG_PM */
3639                 /*
3640                  * this is a wmi data packet
3641                  */
3642                  // NWF
3643
3644                 if (processDot11Hdr) {
3645                     minHdrLen = sizeof(WMI_DATA_HDR) + sizeof(struct ieee80211_frame) + sizeof(ATH_LLC_SNAP_HDR);
3646                 } else {
3647                     minHdrLen = sizeof (WMI_DATA_HDR) + sizeof(ATH_MAC_HDR) +
3648                           sizeof(ATH_LLC_SNAP_HDR);
3649                 }
3650
3651                 /* In the case of AP mode we may receive NULL data frames
3652                  * that do not have LLC hdr. They are 16 bytes in size.
3653                  * Allow these frames in the AP mode.
3654                  * ACL data frames don't follow ethernet frame bounds for
3655                  * min length
3656                  */
3657                 if (ar->arNetworkType != AP_NETWORK &&  !is_acl_data_frame &&
3658                     ((pPacket->ActualLength < minHdrLen) ||
3659                     (pPacket->ActualLength > AR6000_MAX_RX_MESSAGE_SIZE)))
3660                 {
3661                     /*
3662                      * packet is too short or too long
3663                      */
3664                     AR_DEBUG_PRINTF(ATH_DEBUG_INFO,("TOO SHORT or TOO LONG\n"));
3665                     AR6000_STAT_INC(ar, rx_errors);
3666                     AR6000_STAT_INC(ar, rx_length_errors);
3667                     A_NETBUF_FREE(skb);
3668                 } else {
3669                     A_UINT16 seq_no;
3670                     A_UINT8 meta_type;
3671
3672 #if 0
3673                     /* Access RSSI values here */
3674                     AR_DEBUG_PRINTF(ATH_DEBUG_INFO,("RSSI %d\n",
3675                         ((WMI_DATA_HDR *) A_NETBUF_DATA(skb))->rssi));
3676 #endif
3677                     /* Get the Power save state of the STA */
3678                     if (ar->arNetworkType == AP_NETWORK) {
3679                         sta_t *conn = NULL;
3680                         A_UINT8 psState=0,prevPsState;
3681                         ATH_MAC_HDR *datap=NULL;
3682                         A_UINT16 offset;
3683
3684                         meta_type = WMI_DATA_HDR_GET_META(dhdr);
3685
3686                         psState = (((WMI_DATA_HDR *)A_NETBUF_DATA(skb))->info
3687                                      >> WMI_DATA_HDR_PS_SHIFT) & WMI_DATA_HDR_PS_MASK;
3688
3689                         offset = sizeof(WMI_DATA_HDR);
3690
3691                         switch (meta_type) {
3692                             case 0:
3693                                 break;
3694                             case WMI_META_VERSION_1:
3695                                 offset += sizeof(WMI_RX_META_V1);
3696                                 break;
3697 #ifdef CONFIG_CHECKSUM_OFFLOAD
3698                             case WMI_META_VERSION_2:
3699                                 offset += sizeof(WMI_RX_META_V2);
3700                                 break;
3701 #endif
3702                             default:
3703                                 break;
3704                         }
3705
3706                         datap = (ATH_MAC_HDR *)(A_NETBUF_DATA(skb)+offset);
3707                         conn = ieee80211_find_conn(ar, datap->srcMac);
3708
3709                         if (conn) {
3710                             /* if there is a change in PS state of the STA,
3711                              * take appropriate steps.
3712                              * 1. If Sleep-->Awake, flush the psq for the STA
3713                              *    Clear the PVB for the STA.
3714                              * 2. If Awake-->Sleep, Starting queueing frames
3715                              * the STA.
3716                              */
3717                             prevPsState = STA_IS_PWR_SLEEP(conn);
3718                             if (psState) {
3719                                 STA_SET_PWR_SLEEP(conn);
3720                             } else {
3721                                 STA_CLR_PWR_SLEEP(conn);
3722                             }
3723
3724                             if (prevPsState ^ STA_IS_PWR_SLEEP(conn)) {
3725
3726                                 if (!STA_IS_PWR_SLEEP(conn)) {
3727
3728                                     A_MUTEX_LOCK(&conn->psqLock);
3729                                     while (!A_NETBUF_QUEUE_EMPTY(&conn->psq)) {
3730                                         struct sk_buff *skb=NULL;
3731
3732                                         skb = A_NETBUF_DEQUEUE(&conn->psq);
3733                                         A_MUTEX_UNLOCK(&conn->psqLock);
3734                                         ar6000_data_tx(skb,ar->arNetDev);
3735                                         A_MUTEX_LOCK(&conn->psqLock);
3736                                     }
3737                                     A_MUTEX_UNLOCK(&conn->psqLock);
3738                                     /* Clear the PVB for this STA */
3739                                     wmi_set_pvb_cmd(ar->arWmi, conn->aid, 0);
3740                                 }
3741                             }
3742                         } else {
3743                             /* This frame is from a STA that is not associated*/
3744                             A_ASSERT(FALSE);
3745                         }
3746
3747                         /* Drop NULL data frames here */
3748                         if((pPacket->ActualLength < minHdrLen) ||
3749                                 (pPacket->ActualLength > AR6000_MAX_RX_MESSAGE_SIZE)) {
3750                             A_NETBUF_FREE(skb);
3751                             goto rx_done;
3752                         }
3753                     }
3754
3755                     is_amsdu = WMI_DATA_HDR_IS_AMSDU(dhdr);
3756                     tid = WMI_DATA_HDR_GET_UP(dhdr);
3757                     seq_no = WMI_DATA_HDR_GET_SEQNO(dhdr);
3758                     meta_type = WMI_DATA_HDR_GET_META(dhdr);
3759                     containsDot11Hdr = WMI_DATA_HDR_GET_DOT11(dhdr);
3760
3761                     wmi_data_hdr_remove(ar->arWmi, skb);
3762
3763                     switch (meta_type) {
3764                         case WMI_META_VERSION_1:
3765                             {
3766                                 WMI_RX_META_V1 *pMeta = (WMI_RX_META_V1 *)A_NETBUF_DATA(skb);
3767                                 A_PRINTF("META %d %d %d %d %x\n", pMeta->status, pMeta->rix, pMeta->rssi, pMeta->channel, pMeta->flags);
3768                                 A_NETBUF_PULL((void*)skb, sizeof(WMI_RX_META_V1));
3769                                 break;
3770                             }
3771 #ifdef CONFIG_CHECKSUM_OFFLOAD
3772                         case WMI_META_VERSION_2:
3773                             {
3774                                 WMI_RX_META_V2 *pMeta = (WMI_RX_META_V2 *)A_NETBUF_DATA(skb);
3775                                 if(pMeta->csumFlags & 0x1){
3776                                     skb->ip_summed=CHECKSUM_COMPLETE;
3777                                     skb->csum=(pMeta->csum);
3778                                 }
3779                                 A_NETBUF_PULL((void*)skb, sizeof(WMI_RX_META_V2));
3780                                 break;
3781                             }
3782 #endif
3783                         default:
3784                             break;
3785                     }
3786
3787                     A_ASSERT(status == A_OK);
3788
3789                     /* NWF: print the 802.11 hdr bytes */
3790                     if(containsDot11Hdr) {
3791                         status = wmi_dot11_hdr_remove(ar->arWmi,skb);
3792                     } else if(!is_amsdu && !is_acl_data_frame) {
3793                         status = wmi_dot3_2_dix(skb);
3794                     }
3795
3796                     if (status != A_OK) {
3797                         /* Drop frames that could not be processed (lack of memory, etc.) */
3798                         A_NETBUF_FREE(skb);
3799                         goto rx_done;
3800                     }
3801
3802                     if (is_acl_data_frame) {
3803                         A_NETBUF_PUSH(skb, sizeof(int));
3804                         *((short *)A_NETBUF_DATA(skb)) = WMI_ACL_DATA_EVENTID;
3805                         /* send the data packet to PAL driver */
3806                         if(ar6k_pal_config_g.fpar6k_pal_recv_pkt) {
3807                                 if((*ar6k_pal_config_g.fpar6k_pal_recv_pkt)(ar->hcipal_info, skb) == TRUE)
3808                                         goto rx_done;
3809                         }
3810                     }
3811
3812                     if ((ar->arNetDev->flags & IFF_UP) == IFF_UP) {
3813                         if (ar->arNetworkType == AP_NETWORK) {
3814                             struct sk_buff *skb1 = NULL;
3815                             ATH_MAC_HDR *datap;
3816
3817                             datap = (ATH_MAC_HDR *)A_NETBUF_DATA(skb);
3818                             if (IEEE80211_IS_MULTICAST(datap->dstMac)) {
3819                                 /* Bcast/Mcast frames should be sent to the OS
3820                                  * stack as well as on the air.
3821                                  */
3822                                 skb1 = skb_copy(skb,GFP_ATOMIC);
3823                             } else {
3824                                 /* Search for a connected STA with dstMac as
3825                                  * the Mac address. If found send the frame to
3826                                  * it on the air else send the frame up the
3827                                  * stack
3828                                  */
3829                                 sta_t *conn = NULL;
3830                                 conn = ieee80211_find_conn(ar, datap->dstMac);
3831
3832                                 if (conn && ar->intra_bss) {
3833                                     skb1 = skb;
3834                                     skb = NULL;
3835                                 } else if(conn && !ar->intra_bss) {
3836                                     A_NETBUF_FREE(skb);
3837                                     skb = NULL;
3838                                 }
3839                             }
3840                             if (skb1) {
3841                                 ar6000_data_tx(skb1, ar->arNetDev);
3842                             }
3843                         }
3844                     }
3845 #ifdef ATH_AR6K_11N_SUPPORT
3846                     aggr_process_recv_frm(ar->aggr_cntxt, tid, seq_no, is_amsdu, (void **)&skb);
3847 #endif
3848                     ar6000_deliver_frames_to_nw_stack((void *) ar->arNetDev, (void *)skb);
3849                 }
3850             }
3851     } else {
3852         if (EPPING_ALIGNMENT_PAD > 0) {
3853             A_NETBUF_PULL(skb, EPPING_ALIGNMENT_PAD);
3854         }
3855         ar6000_deliver_frames_to_nw_stack((void *)ar->arNetDev, (void *)skb);
3856     }
3857
3858 rx_done:
3859
3860     return;
3861 }
3862
3863 static void
3864 ar6000_deliver_frames_to_nw_stack(void *dev, void *osbuf)
3865 {
3866     struct sk_buff *skb = (struct sk_buff *)osbuf;
3867
3868     if(skb) {
3869         skb->dev = dev;
3870         if ((skb->dev->flags & IFF_UP) == IFF_UP) {
3871 #ifdef CONFIG_PM 
3872             ar6000_check_wow_status((AR_SOFTC_T *)ar6k_priv(dev), skb, FALSE);   
3873 #endif /* CONFIG_PM */
3874             skb->protocol = eth_type_trans(skb, skb->dev);
3875         /*
3876          * If this routine is called on a ISR (Hard IRQ) or DSR (Soft IRQ)
3877          * or tasklet use the netif_rx to deliver the packet to the stack
3878          * netif_rx will queue the packet onto the receive queue and mark
3879          * the softirq thread has a pending action to complete. Kernel will 
3880          * schedule the softIrq kernel thread after processing the DSR.
3881          *
3882          * If this routine is called on a process context, use netif_rx_ni
3883          * which will schedle the softIrq kernel thread after queuing the packet.
3884          */
3885             if (in_interrupt()) {
3886                 netif_rx(skb);
3887             } else {
3888                 netif_rx_ni(skb);
3889             }
3890         } else {
3891             A_NETBUF_FREE(skb);
3892         }
3893     }
3894 }
3895
3896 #if 0
3897 static void
3898 ar6000_deliver_frames_to_bt_stack(void *dev, void *osbuf)
3899 {
3900     struct sk_buff *skb = (struct sk_buff *)osbuf;
3901
3902     if(skb) {
3903         skb->dev = dev;
3904         if ((skb->dev->flags & IFF_UP) == IFF_UP) {
3905             skb->protocol = htons(ETH_P_CONTROL);
3906             netif_rx(skb);
3907         } else {
3908             A_NETBUF_FREE(skb);
3909         }
3910     }
3911 }
3912 #endif
3913
3914 static void
3915 ar6000_rx_refill(void *Context, HTC_ENDPOINT_ID Endpoint)
3916 {
3917     AR_SOFTC_T  *ar = (AR_SOFTC_T *)Context;
3918     void        *osBuf;
3919     int         RxBuffers;
3920     int         buffersToRefill;
3921     HTC_PACKET  *pPacket;
3922     HTC_PACKET_QUEUE queue;
3923
3924     buffersToRefill = (int)AR6000_MAX_RX_BUFFERS -
3925                                     HTCGetNumRecvBuffers(ar->arHtcTarget, Endpoint);
3926
3927     if (buffersToRefill <= 0) {
3928             /* fast return, nothing to fill */
3929         return;
3930     }
3931
3932     INIT_HTC_PACKET_QUEUE(&queue);
3933
3934     AR_DEBUG_PRINTF(ATH_DEBUG_WLAN_RX,("ar6000_rx_refill: providing htc with %d buffers at eid=%d\n",
3935                     buffersToRefill, Endpoint));
3936
3937     for (RxBuffers = 0; RxBuffers < buffersToRefill; RxBuffers++) {
3938         osBuf = A_NETBUF_ALLOC(AR6000_BUFFER_SIZE);
3939         if (NULL == osBuf) {
3940             break;
3941         }
3942             /* the HTC packet wrapper is at the head of the reserved area
3943              * in the skb */
3944         pPacket = (HTC_PACKET *)(A_NETBUF_HEAD(osBuf));
3945             /* set re-fill info */
3946         SET_HTC_PACKET_INFO_RX_REFILL(pPacket,osBuf,A_NETBUF_DATA(osBuf),AR6000_BUFFER_SIZE,Endpoint);
3947             /* add to queue */
3948         HTC_PACKET_ENQUEUE(&queue,pPacket);
3949     }
3950
3951     if (!HTC_QUEUE_EMPTY(&queue)) {
3952             /* add packets */
3953         HTCAddReceivePktMultiple(ar->arHtcTarget, &queue);
3954     }
3955
3956 }
3957
3958   /* clean up our amsdu buffer list */
3959 static void ar6000_cleanup_amsdu_rxbufs(AR_SOFTC_T *ar)
3960 {
3961     HTC_PACKET  *pPacket;
3962     void        *osBuf;
3963
3964         /* empty AMSDU buffer queue and free OS bufs */
3965     while (TRUE) {
3966
3967         AR6000_SPIN_LOCK(&ar->arLock, 0);
3968         pPacket = HTC_PACKET_DEQUEUE(&ar->amsdu_rx_buffer_queue);
3969         AR6000_SPIN_UNLOCK(&ar->arLock, 0);
3970
3971         if (NULL == pPacket) {
3972             break;
3973         }
3974
3975         osBuf = pPacket->pPktContext;
3976         if (NULL == osBuf) {
3977             A_ASSERT(FALSE);
3978             break;
3979         }
3980
3981         A_NETBUF_FREE(osBuf);
3982     }
3983
3984 }
3985
3986
3987     /* refill the amsdu buffer list */
3988 static void ar6000_refill_amsdu_rxbufs(AR_SOFTC_T *ar, int Count)
3989 {
3990     HTC_PACKET  *pPacket;
3991     void        *osBuf;
3992
3993     while (Count > 0) {
3994         osBuf = A_NETBUF_ALLOC(AR6000_AMSDU_BUFFER_SIZE);
3995         if (NULL == osBuf) {
3996             break;
3997         }
3998             /* the HTC packet wrapper is at the head of the reserved area
3999              * in the skb */
4000         pPacket = (HTC_PACKET *)(A_NETBUF_HEAD(osBuf));
4001             /* set re-fill info */
4002         SET_HTC_PACKET_INFO_RX_REFILL(pPacket,osBuf,A_NETBUF_DATA(osBuf),AR6000_AMSDU_BUFFER_SIZE,0);
4003
4004         AR6000_SPIN_LOCK(&ar->arLock, 0);
4005             /* put it in the list */
4006         HTC_PACKET_ENQUEUE(&ar->amsdu_rx_buffer_queue,pPacket);
4007         AR6000_SPIN_UNLOCK(&ar->arLock, 0);
4008         Count--;
4009     }
4010
4011 }
4012
4013     /* callback to allocate a large receive buffer for a pending packet.  This function is called when
4014      * an HTC packet arrives whose length exceeds a threshold value
4015      *
4016      * We use a pre-allocated list of buffers of maximum AMSDU size (4K).  Under linux it is more optimal to
4017      * keep the allocation size the same to optimize cached-slab allocations.
4018      *
4019      * */
4020 static HTC_PACKET *ar6000_alloc_amsdu_rxbuf(void *Context, HTC_ENDPOINT_ID Endpoint, int Length)
4021 {
4022     HTC_PACKET  *pPacket = NULL;
4023     AR_SOFTC_T  *ar = (AR_SOFTC_T *)Context;
4024     int         refillCount = 0;
4025
4026     AR_DEBUG_PRINTF(ATH_DEBUG_WLAN_RX,("ar6000_alloc_amsdu_rxbuf: eid=%d, Length:%d\n",Endpoint,Length));
4027
4028     do {
4029
4030         if (Length <= AR6000_BUFFER_SIZE) {
4031                 /* shouldn't be getting called on normal sized packets */
4032             A_ASSERT(FALSE);
4033             break;
4034         }
4035
4036         if (Length > AR6000_AMSDU_BUFFER_SIZE) {
4037             A_ASSERT(FALSE);
4038             break;
4039         }
4040
4041         AR6000_SPIN_LOCK(&ar->arLock, 0);
4042             /* allocate a packet from the list */
4043         pPacket = HTC_PACKET_DEQUEUE(&ar->amsdu_rx_buffer_queue);
4044             /* see if we need to refill again */
4045         refillCount = AR6000_MAX_AMSDU_RX_BUFFERS - HTC_PACKET_QUEUE_DEPTH(&ar->amsdu_rx_buffer_queue);
4046         AR6000_SPIN_UNLOCK(&ar->arLock, 0);
4047
4048         if (NULL == pPacket) {
4049             break;
4050         }
4051             /* set actual endpoint ID */
4052         pPacket->Endpoint = Endpoint;
4053
4054     } while (FALSE);
4055
4056     if (refillCount >= AR6000_AMSDU_REFILL_THRESHOLD) {
4057         ar6000_refill_amsdu_rxbufs(ar,refillCount);
4058     }
4059
4060     return pPacket;
4061 }
4062
4063 static void     
4064 ar6000_set_multicast_list(struct net_device *dev)
4065 {
4066     AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("ar6000: Multicast filter not supported\n"));
4067 }
4068
4069 static struct net_device_stats *
4070 ar6000_get_stats(struct net_device *dev)
4071 {
4072     AR_SOFTC_T *ar = (AR_SOFTC_T *)ar6k_priv(dev);
4073     return &ar->arNetStats;
4074 }
4075
4076 static struct iw_statistics *
4077 ar6000_get_iwstats(struct net_device * dev)
4078 {
4079     AR_SOFTC_T *ar = (AR_SOFTC_T *)ar6k_priv(dev);
4080     TARGET_STATS *pStats = &ar->arTargetStats;
4081     struct iw_statistics * pIwStats = &ar->arIwStats;
4082     int rtnllocked;
4083
4084     if (ar->bIsDestroyProgress || ar->arWmiReady == FALSE || ar->arWlanState == WLAN_DISABLED)
4085     {
4086         pIwStats->status = 0;
4087         pIwStats->qual.qual = 0;
4088         pIwStats->qual.level =0;
4089         pIwStats->qual.noise = 0;
4090         pIwStats->discard.code =0;
4091         pIwStats->discard.retries=0;
4092         pIwStats->miss.beacon =0;
4093         return pIwStats;
4094     }
4095
4096     /*
4097      * The in_atomic function is used to determine if the scheduling is
4098      * allowed in the current context or not. This was introduced in 2.6
4099      * From what I have read on the differences between 2.4 and 2.6, the
4100      * 2.4 kernel did not support preemption and so this check might not
4101      * be required for 2.4 kernels.
4102      */
4103     if (in_atomic())
4104     {
4105         wmi_get_stats_cmd(ar->arWmi);
4106
4107         pIwStats->status = 1 ;
4108         pIwStats->qual.qual = pStats->cs_aveBeacon_rssi - 161;
4109         pIwStats->qual.level =pStats->cs_aveBeacon_rssi; /* noise is -95 dBm */
4110         pIwStats->qual.noise = pStats->noise_floor_calibation;
4111         pIwStats->discard.code = pStats->rx_decrypt_err;
4112         pIwStats->discard.retries = pStats->tx_retry_cnt;
4113         pIwStats->miss.beacon = pStats->cs_bmiss_cnt;
4114         return pIwStats;
4115     }
4116
4117     dev_hold(dev);   
4118     rtnllocked = rtnl_is_locked();
4119     if (rtnllocked) {
4120         rtnl_unlock();
4121     }
4122     pIwStats->status = 0;
4123
4124     if (down_interruptible(&ar->arSem)) {
4125         goto err_exit;
4126     }
4127     
4128     do {
4129
4130         if (ar->bIsDestroyProgress || ar->arWlanState == WLAN_DISABLED) {
4131             break;
4132         }
4133     
4134         ar->statsUpdatePending = TRUE;
4135     
4136         if(wmi_get_stats_cmd(ar->arWmi) != A_OK) {
4137             break;
4138         }
4139     
4140         wait_event_interruptible_timeout(arEvent, ar->statsUpdatePending == FALSE, wmitimeout * HZ);
4141         if (signal_pending(current)) {
4142             AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("ar6000 : WMI get stats timeout \n"));
4143             break;
4144         }
4145         pIwStats->status = 1 ;
4146         pIwStats->qual.qual = pStats->cs_aveBeacon_rssi - 161;
4147         pIwStats->qual.level =pStats->cs_aveBeacon_rssi;  /* noise is -95 dBm */
4148         pIwStats->qual.noise = pStats->noise_floor_calibation;
4149         pIwStats->discard.code = pStats->rx_decrypt_err;
4150         pIwStats->discard.retries = pStats->tx_retry_cnt;
4151         pIwStats->miss.beacon = pStats->cs_bmiss_cnt;
4152     } while (0);
4153     up(&ar->arSem);
4154
4155 err_exit:
4156     if (rtnllocked) {
4157         rtnl_lock();
4158     }
4159     dev_put(dev);
4160     return pIwStats;
4161 }
4162
4163 void
4164 ar6000_ready_event(void *devt, A_UINT8 *datap, A_UINT8 phyCap, A_UINT32 sw_ver, A_UINT32 abi_ver)
4165 {
4166     AR_SOFTC_T *ar = (AR_SOFTC_T *)devt;
4167     struct net_device *dev = ar->arNetDev;
4168
4169     A_MEMCPY(dev->dev_addr, datap, AR6000_ETH_ADDR_LEN);
4170     AR_DEBUG_PRINTF(ATH_DEBUG_INFO,("mac address = %2.2x:%2.2x:%2.2x:%2.2x:%2.2x:%2.2x\n",
4171         dev->dev_addr[0], dev->dev_addr[1],
4172         dev->dev_addr[2], dev->dev_addr[3],
4173         dev->dev_addr[4], dev->dev_addr[5]));
4174
4175     ar->arPhyCapability = phyCap;
4176     ar->arVersion.wlan_ver = sw_ver;
4177     ar->arVersion.abi_ver = abi_ver;
4178
4179     /* Indicate to the waiting thread that the ready event was received */
4180     ar->arWmiReady = TRUE;
4181     wake_up(&arEvent);
4182
4183 #if WLAN_CONFIG_IGNORE_POWER_SAVE_FAIL_EVENT_DURING_SCAN
4184     wmi_pmparams_cmd(ar->arWmi, 0, 1, 0, 0, 1, IGNORE_POWER_SAVE_FAIL_EVENT_DURING_SCAN);
4185 #endif
4186 #if WLAN_CONFIG_DONOT_IGNORE_BARKER_IN_ERP
4187     wmi_set_lpreamble_cmd(ar->arWmi, 0, WMI_DONOT_IGNORE_BARKER_IN_ERP);
4188 #endif
4189     wmi_set_keepalive_cmd(ar->arWmi, WLAN_CONFIG_KEEP_ALIVE_INTERVAL);
4190 #if WLAN_CONFIG_DISABLE_11N
4191     {
4192         WMI_SET_HT_CAP_CMD htCap;
4193
4194         A_MEMZERO(&htCap, sizeof(WMI_SET_HT_CAP_CMD));
4195         htCap.band = 0;
4196         wmi_set_ht_cap_cmd(ar->arWmi, &htCap);
4197
4198         htCap.band = 1;
4199         wmi_set_ht_cap_cmd(ar->arWmi, &htCap);
4200     }
4201 #endif /* WLAN_CONFIG_DISABLE_11N */
4202
4203 #ifdef ATH6K_CONFIG_OTA_MODE
4204     wmi_powermode_cmd(ar->arWmi, MAX_PERF_POWER);
4205 #endif
4206     wmi_disctimeout_cmd(ar->arWmi, WLAN_CONFIG_DISCONNECT_TIMEOUT);
4207 }
4208
4209 void
4210 add_new_sta(AR_SOFTC_T *ar, A_UINT8 *mac, A_UINT16 aid, A_UINT8 *wpaie,
4211             A_UINT8 ielen, A_UINT8 keymgmt, A_UINT8 ucipher, A_UINT8 auth)
4212 {
4213     A_UINT8    free_slot=aid-1;
4214
4215         A_MEMCPY(ar->sta_list[free_slot].mac, mac, ATH_MAC_LEN);
4216         A_MEMCPY(ar->sta_list[free_slot].wpa_ie, wpaie, ielen);
4217         ar->sta_list[free_slot].aid = aid;
4218         ar->sta_list[free_slot].keymgmt = keymgmt;
4219         ar->sta_list[free_slot].ucipher = ucipher;
4220         ar->sta_list[free_slot].auth = auth;
4221         ar->sta_list_index = ar->sta_list_index | (1 << free_slot);
4222     ar->arAPStats.sta[free_slot].aid = aid;
4223 }
4224
4225 void
4226 ar6000_connect_event(AR_SOFTC_T *ar, A_UINT16 channel, A_UINT8 *bssid,
4227                      A_UINT16 listenInterval, A_UINT16 beaconInterval,
4228                      NETWORK_TYPE networkType, A_UINT8 beaconIeLen,
4229                      A_UINT8 assocReqLen, A_UINT8 assocRespLen,
4230                      A_UINT8 *assocInfo)
4231 {
4232     union iwreq_data wrqu;
4233     int i, beacon_ie_pos, assoc_resp_ie_pos, assoc_req_ie_pos;
4234     static const char *tag1 = "ASSOCINFO(ReqIEs=";
4235     static const char *tag2 = "ASSOCRESPIE=";
4236     static const char *beaconIetag = "BEACONIE=";
4237     char buf[WMI_CONTROL_MSG_MAX_LEN * 2 + strlen(tag1) + 1];
4238     char *pos;
4239     A_UINT8 key_op_ctrl;
4240     unsigned long flags;
4241     struct ieee80211req_key *ik;
4242     CRYPTO_TYPE keyType = NONE_CRYPT;
4243
4244     if(ar->arNetworkType & AP_NETWORK) {
4245         struct net_device *dev = ar->arNetDev;
4246         if(A_MEMCMP(dev->dev_addr, bssid, ATH_MAC_LEN)==0) {
4247             ar->arACS = channel;
4248             ik = &ar->ap_mode_bkey;
4249
4250             switch(ar->arAuthMode) {
4251             case NONE_AUTH:
4252                 if(ar->arPairwiseCrypto == WEP_CRYPT) {
4253                     ar6000_install_static_wep_keys(ar);
4254                 }
4255 #ifdef WAPI_ENABLE
4256                 else if(ar->arPairwiseCrypto == WAPI_CRYPT) {
4257                     ap_set_wapi_key(ar, ik);
4258                 }
4259 #endif
4260                 break;
4261             case WPA_PSK_AUTH:
4262             case WPA2_PSK_AUTH:
4263             case (WPA_PSK_AUTH|WPA2_PSK_AUTH):
4264                 switch (ik->ik_type) {
4265                     case IEEE80211_CIPHER_TKIP:
4266                         keyType = TKIP_CRYPT;
4267                         break;
4268                     case IEEE80211_CIPHER_AES_CCM:
4269                         keyType = AES_CRYPT;
4270                         break;
4271                     default:
4272                        goto skip_key;
4273                 }
4274                 wmi_addKey_cmd(ar->arWmi, ik->ik_keyix, keyType, GROUP_USAGE,
4275                                 ik->ik_keylen, (A_UINT8 *)&ik->ik_keyrsc,
4276                                 ik->ik_keydata, KEY_OP_INIT_VAL, ik->ik_macaddr,
4277                                 SYNC_BOTH_WMIFLAG);
4278
4279                 break;
4280             }
4281 skip_key:
4282             ar->arConnected  = TRUE;
4283             return;
4284         }
4285
4286         A_PRINTF("NEW STA %2.2x:%2.2x:%2.2x:%2.2x:%2.2x:%2.2x \n "
4287             " AID=%d \n", bssid[0], bssid[1], bssid[2],
4288              bssid[3], bssid[4], bssid[5], channel);
4289         switch ((listenInterval>>8)&0xFF) {
4290             case OPEN_AUTH:
4291                 A_PRINTF("AUTH: OPEN\n");
4292                 break;
4293             case SHARED_AUTH:
4294                 A_PRINTF("AUTH: SHARED\n");
4295                 break;
4296             default:
4297                 A_PRINTF("AUTH: Unknown\n");
4298                 break;
4299         };
4300         switch (listenInterval&0xFF) {
4301             case WPA_PSK_AUTH:
4302                 A_PRINTF("KeyMgmt: WPA-PSK\n");
4303                 break;
4304             case WPA2_PSK_AUTH:
4305                 A_PRINTF("KeyMgmt: WPA2-PSK\n");
4306                 break;
4307             default:
4308                 A_PRINTF("KeyMgmt: NONE\n");
4309                 break;
4310         };
4311         switch (beaconInterval) {
4312             case AES_CRYPT:
4313                 A_PRINTF("Cipher: AES\n");
4314                 break;
4315             case TKIP_CRYPT:
4316                 A_PRINTF("Cipher: TKIP\n");
4317                 break;
4318             case WEP_CRYPT:
4319                 A_PRINTF("Cipher: WEP\n");
4320                 break;
4321 #ifdef WAPI_ENABLE
4322             case WAPI_CRYPT:
4323                 A_PRINTF("Cipher: WAPI\n");
4324                 break;
4325 #endif
4326             default:
4327                 A_PRINTF("Cipher: NONE\n");
4328                 break;
4329         };
4330
4331         add_new_sta(ar, bssid, channel /*aid*/,
4332             assocInfo /* WPA IE */, assocRespLen /* IE len */,
4333             listenInterval&0xFF /* Keymgmt */, beaconInterval /* cipher */,
4334             (listenInterval>>8)&0xFF /* auth alg */);
4335
4336         /* Send event to application */
4337         A_MEMZERO(&wrqu, sizeof(wrqu));
4338         A_MEMCPY(wrqu.addr.sa_data, bssid, ATH_MAC_LEN);
4339         wireless_send_event(ar->arNetDev, IWEVREGISTERED, &wrqu, NULL);
4340         /* In case the queue is stopped when we switch modes, this will
4341          * wake it up
4342          */
4343         netif_wake_queue(ar->arNetDev);
4344         return;
4345     }
4346
4347 #ifdef ATH6K_CONFIG_CFG80211
4348     ar6k_cfg80211_connect_event(ar, channel, bssid,
4349                                 listenInterval, beaconInterval,
4350                                 networkType, beaconIeLen,
4351                                 assocReqLen, assocRespLen,
4352                                 assocInfo);
4353 #endif /* ATH6K_CONFIG_CFG80211 */
4354
4355     A_MEMCPY(ar->arBssid, bssid, sizeof(ar->arBssid));
4356     ar->arBssChannel = channel;
4357
4358     A_PRINTF("AR6000 connected event on freq %d ", channel);
4359     A_PRINTF("with bssid %2.2x:%2.2x:%2.2x:%2.2x:%2.2x:%2.2x "
4360             " listenInterval=%d, beaconInterval = %d, beaconIeLen = %d assocReqLen=%d"
4361             " assocRespLen =%d\n",
4362              bssid[0], bssid[1], bssid[2],
4363              bssid[3], bssid[4], bssid[5],
4364              listenInterval, beaconInterval,
4365              beaconIeLen, assocReqLen, assocRespLen);
4366     if (networkType & ADHOC_NETWORK) {
4367         if (networkType & ADHOC_CREATOR) {
4368             A_PRINTF("Network: Adhoc (Creator)\n");
4369         } else {
4370             A_PRINTF("Network: Adhoc (Joiner)\n");
4371         }
4372     } else {
4373         A_PRINTF("Network: Infrastructure\n");
4374     }
4375
4376     if ((ar->arNetworkType == INFRA_NETWORK)) {
4377         wmi_listeninterval_cmd(ar->arWmi, ar->arListenIntervalT, ar->arListenIntervalB);
4378     }
4379
4380     if (beaconIeLen && (sizeof(buf) > (9 + beaconIeLen * 2))) {
4381         AR_DEBUG_PRINTF(ATH_DEBUG_WLAN_CONNECT,("\nBeaconIEs= "));
4382
4383         beacon_ie_pos = 0;
4384         A_MEMZERO(buf, sizeof(buf));
4385         sprintf(buf, "%s", beaconIetag);
4386         pos = buf + 9;
4387         for (i = beacon_ie_pos; i < beacon_ie_pos + beaconIeLen; i++) {
4388             AR_DEBUG_PRINTF(ATH_DEBUG_WLAN_CONNECT,("%2.2x ", assocInfo[i]));
4389             sprintf(pos, "%2.2x", assocInfo[i]);
4390             pos += 2;
4391         }
4392         AR_DEBUG_PRINTF(ATH_DEBUG_WLAN_CONNECT,("\n"));
4393
4394         A_MEMZERO(&wrqu, sizeof(wrqu));
4395         wrqu.data.length = strlen(buf);
4396         wireless_send_event(ar->arNetDev, IWEVCUSTOM, &wrqu, buf);
4397     }
4398
4399     if (assocRespLen && (sizeof(buf) > (12 + (assocRespLen * 2))))
4400     {
4401         assoc_resp_ie_pos = beaconIeLen + assocReqLen +
4402                             sizeof(A_UINT16)  +  /* capinfo*/
4403                             sizeof(A_UINT16)  +  /* status Code */
4404                             sizeof(A_UINT16)  ;  /* associd */
4405         A_MEMZERO(buf, sizeof(buf));
4406         sprintf(buf, "%s", tag2);
4407         pos = buf + 12;
4408         AR_DEBUG_PRINTF(ATH_DEBUG_WLAN_CONNECT,("\nAssocRespIEs= "));
4409         /*
4410          * The Association Response Frame w.o. the WLAN header is delivered to
4411          * the host, so skip over to the IEs
4412          */
4413         for (i = assoc_resp_ie_pos; i < assoc_resp_ie_pos + assocRespLen - 6; i++)
4414         {
4415             AR_DEBUG_PRINTF(ATH_DEBUG_WLAN_CONNECT,("%2.2x ", assocInfo[i]));
4416             sprintf(pos, "%2.2x", assocInfo[i]);
4417             pos += 2;
4418         }
4419         AR_DEBUG_PRINTF(ATH_DEBUG_WLAN_CONNECT,("\n"));
4420
4421         A_MEMZERO(&wrqu, sizeof(wrqu));
4422         wrqu.data.length = strlen(buf);
4423         wireless_send_event(ar->arNetDev, IWEVCUSTOM, &wrqu, buf);
4424     }
4425
4426     if (assocReqLen && (sizeof(buf) > (17 + (assocReqLen * 2)))) {
4427         /*
4428          * assoc Request includes capability and listen interval. Skip these.
4429          */
4430         assoc_req_ie_pos =  beaconIeLen +
4431                             sizeof(A_UINT16)  +  /* capinfo*/
4432                             sizeof(A_UINT16);    /* listen interval */
4433
4434         A_MEMZERO(buf, sizeof(buf));
4435         sprintf(buf, "%s", tag1);
4436         pos = buf + 17;
4437         AR_DEBUG_PRINTF(ATH_DEBUG_WLAN_CONNECT,("AssocReqIEs= "));
4438         for (i = assoc_req_ie_pos; i < assoc_req_ie_pos + assocReqLen - 4; i++) {
4439             AR_DEBUG_PRINTF(ATH_DEBUG_WLAN_CONNECT,("%2.2x ", assocInfo[i]));
4440             sprintf(pos, "%2.2x", assocInfo[i]);
4441             pos += 2;;
4442         }
4443         AR_DEBUG_PRINTF(ATH_DEBUG_WLAN_CONNECT,("\n"));
4444
4445         A_MEMZERO(&wrqu, sizeof(wrqu));
4446         wrqu.data.length = strlen(buf);
4447         wireless_send_event(ar->arNetDev, IWEVCUSTOM, &wrqu, buf);
4448     }
4449
4450 #ifdef USER_KEYS
4451     if (ar->user_savedkeys_stat == USER_SAVEDKEYS_STAT_RUN &&
4452         ar->user_saved_keys.keyOk == TRUE)
4453     {
4454         key_op_ctrl = KEY_OP_VALID_MASK & ~KEY_OP_INIT_TSC;
4455
4456         if (ar->user_key_ctrl & AR6000_USER_SETKEYS_RSC_UNCHANGED) {
4457             key_op_ctrl &= ~KEY_OP_INIT_RSC;
4458         } else {
4459             key_op_ctrl |= KEY_OP_INIT_RSC;
4460         }
4461         ar6000_reinstall_keys(ar, key_op_ctrl);
4462     }
4463 #endif /* USER_KEYS */
4464
4465     netif_wake_queue(ar->arNetDev);
4466
4467     /* For CFG80211 the key configuration and the default key comes in after connect so no point in plumbing invalid keys */
4468 #ifndef ATH6K_CONFIG_CFG80211
4469     if ((networkType & ADHOC_NETWORK)      &&
4470         (OPEN_AUTH == ar->arDot11AuthMode) &&
4471         (NONE_AUTH == ar->arAuthMode)      &&
4472         (WEP_CRYPT == ar->arPairwiseCrypto))
4473     {
4474         if (!ar->arConnected) {
4475             wmi_addKey_cmd(ar->arWmi,
4476                            ar->arDefTxKeyIndex,
4477                            WEP_CRYPT,
4478                            GROUP_USAGE | TX_USAGE,
4479                            ar->arWepKeyList[ar->arDefTxKeyIndex].arKeyLen,
4480                            NULL,
4481                            ar->arWepKeyList[ar->arDefTxKeyIndex].arKey, KEY_OP_INIT_VAL, NULL,
4482                            NO_SYNC_WMIFLAG);
4483         }
4484     }
4485 #endif /* ATH6K_CONFIG_CFG80211 */
4486
4487     /* Update connect & link status atomically */
4488     spin_lock_irqsave(&ar->arLock, flags);
4489     ar->arConnected  = TRUE;
4490     ar->arConnectPending = FALSE;
4491     netif_carrier_on(ar->arNetDev);
4492     spin_unlock_irqrestore(&ar->arLock, flags);
4493     /* reset the rx aggr state */
4494     aggr_reset_state(ar->aggr_cntxt);
4495     reconnect_flag = 0;
4496
4497     A_MEMZERO(&wrqu, sizeof(wrqu));
4498     A_MEMCPY(wrqu.addr.sa_data, bssid, IEEE80211_ADDR_LEN);
4499     wrqu.addr.sa_family = ARPHRD_ETHER;
4500     wireless_send_event(ar->arNetDev, SIOCGIWAP, &wrqu, NULL);
4501     if ((ar->arNetworkType == ADHOC_NETWORK) && ar->arIbssPsEnable) {
4502         A_MEMZERO(ar->arNodeMap, sizeof(ar->arNodeMap));
4503         ar->arNodeNum = 0;
4504         ar->arNexEpId = ENDPOINT_2;
4505     }
4506    if (!ar->arUserBssFilter) {
4507         wmi_bssfilter_cmd(ar->arWmi, NONE_BSS_FILTER, 0);
4508    }
4509
4510 }
4511
4512 void ar6000_set_numdataendpts(AR_SOFTC_T *ar, A_UINT32 num)
4513 {
4514     A_ASSERT(num <= (HTC_MAILBOX_NUM_MAX - 1));
4515     ar->arNumDataEndPts = num;
4516 }
4517
4518 void
4519 sta_cleanup(AR_SOFTC_T *ar, A_UINT8 i)
4520 {
4521     struct sk_buff *skb;
4522
4523     /* empty the queued pkts in the PS queue if any */
4524     A_MUTEX_LOCK(&ar->sta_list[i].psqLock);
4525     while (!A_NETBUF_QUEUE_EMPTY(&ar->sta_list[i].psq)) {
4526         skb = A_NETBUF_DEQUEUE(&ar->sta_list[i].psq);
4527         A_NETBUF_FREE(skb);
4528     }
4529     A_MUTEX_UNLOCK(&ar->sta_list[i].psqLock);
4530
4531     /* Zero out the state fields */
4532     A_MEMZERO(&ar->arAPStats.sta[ar->sta_list[i].aid-1], sizeof(WMI_PER_STA_STAT));
4533     A_MEMZERO(&ar->sta_list[i].mac, ATH_MAC_LEN);
4534     A_MEMZERO(&ar->sta_list[i].wpa_ie, IEEE80211_MAX_IE);
4535     ar->sta_list[i].aid = 0;
4536     ar->sta_list[i].flags = 0;
4537
4538     ar->sta_list_index = ar->sta_list_index & ~(1 << i);
4539
4540 }
4541
4542 A_UINT8
4543 remove_sta(AR_SOFTC_T *ar, A_UINT8 *mac, A_UINT16 reason)
4544 {
4545     A_UINT8 i, removed=0;
4546
4547     if(IS_MAC_NULL(mac)) {
4548         return removed;
4549     }
4550
4551     if(IS_MAC_BCAST(mac)) {
4552         A_PRINTF("DEL ALL STA\n");
4553         for(i=0; i < AP_MAX_NUM_STA; i++) {
4554             if(!IS_MAC_NULL(ar->sta_list[i].mac)) {
4555                 sta_cleanup(ar, i);
4556                 removed = 1;
4557             }
4558         }
4559     } else {
4560         for(i=0; i < AP_MAX_NUM_STA; i++) {
4561             if(A_MEMCMP(ar->sta_list[i].mac, mac, ATH_MAC_LEN)==0) {
4562                 A_PRINTF("DEL STA %2.2x:%2.2x:%2.2x:%2.2x:%2.2x:%2.2x "
4563                 " aid=%d REASON=%d\n", mac[0], mac[1], mac[2],
4564                  mac[3], mac[4], mac[5], ar->sta_list[i].aid, reason);
4565
4566                 sta_cleanup(ar, i);
4567                 removed = 1;
4568                 break;
4569             }
4570         }
4571     }
4572     return removed;
4573 }
4574
4575 void
4576 ar6000_disconnect_event(AR_SOFTC_T *ar, A_UINT8 reason, A_UINT8 *bssid,
4577                         A_UINT8 assocRespLen, A_UINT8 *assocInfo, A_UINT16 protocolReasonStatus)
4578 {
4579     A_UINT8 i;
4580     unsigned long flags;
4581     union iwreq_data wrqu;
4582
4583     if(ar->arNetworkType & AP_NETWORK) {
4584         union iwreq_data wrqu;
4585         struct sk_buff *skb;
4586
4587         if(!remove_sta(ar, bssid, protocolReasonStatus)) {
4588             return;
4589         }
4590
4591         /* If there are no more associated STAs, empty the mcast PS q */
4592         if (ar->sta_list_index == 0) {
4593             A_MUTEX_LOCK(&ar->mcastpsqLock);
4594             while (!A_NETBUF_QUEUE_EMPTY(&ar->mcastpsq)) {
4595                 skb = A_NETBUF_DEQUEUE(&ar->mcastpsq);
4596                 A_NETBUF_FREE(skb);
4597             }
4598             A_MUTEX_UNLOCK(&ar->mcastpsqLock);
4599
4600             /* Clear the LSB of the BitMapCtl field of the TIM IE */
4601             if (ar->arWmiReady) {
4602                 wmi_set_pvb_cmd(ar->arWmi, MCAST_AID, 0);
4603             }
4604         }
4605
4606         if(!IS_MAC_BCAST(bssid)) {
4607             /* Send event to application */
4608             A_MEMZERO(&wrqu, sizeof(wrqu));
4609             A_MEMCPY(wrqu.addr.sa_data, bssid, ATH_MAC_LEN);
4610             wireless_send_event(ar->arNetDev, IWEVEXPIRED, &wrqu, NULL);
4611         }
4612         return;
4613     }
4614
4615 #ifdef ATH6K_CONFIG_CFG80211
4616     ar6k_cfg80211_disconnect_event(ar, reason, bssid,
4617                                    assocRespLen, assocInfo,
4618                                    protocolReasonStatus);
4619 #endif /* ATH6K_CONFIG_CFG80211 */
4620
4621     /* Send disconnect event to supplicant */
4622     A_MEMZERO(&wrqu, sizeof(wrqu));
4623     wrqu.addr.sa_family = ARPHRD_ETHER;
4624     wireless_send_event(ar->arNetDev, SIOCGIWAP, &wrqu, NULL);
4625
4626     /* it is necessary to clear the host-side rx aggregation state */
4627     aggr_reset_state(ar->aggr_cntxt);
4628
4629     A_UNTIMEOUT(&ar->disconnect_timer);
4630
4631     A_PRINTF("AR6000 disconnected");
4632     if (bssid[0] || bssid[1] || bssid[2] || bssid[3] || bssid[4] || bssid[5]) {
4633         A_PRINTF(" from %2.2x:%2.2x:%2.2x:%2.2x:%2.2x:%2.2x ",
4634                  bssid[0], bssid[1], bssid[2], bssid[3], bssid[4], bssid[5]);
4635     }
4636
4637     AR_DEBUG_PRINTF(ATH_DEBUG_WLAN_CONNECT,("\nDisconnect Reason is %d", reason));
4638     AR_DEBUG_PRINTF(ATH_DEBUG_WLAN_CONNECT,("\nProtocol Reason/Status Code is %d", protocolReasonStatus));
4639     AR_DEBUG_PRINTF(ATH_DEBUG_WLAN_CONNECT,("\nAssocResp Frame = %s",
4640                     assocRespLen ? " " : "NULL"));
4641     for (i = 0; i < assocRespLen; i++) {
4642         if (!(i % 0x10)) {
4643             AR_DEBUG_PRINTF(ATH_DEBUG_WLAN_CONNECT,("\n"));
4644         }
4645         AR_DEBUG_PRINTF(ATH_DEBUG_WLAN_CONNECT,("%2.2x ", assocInfo[i]));
4646     }
4647     AR_DEBUG_PRINTF(ATH_DEBUG_WLAN_CONNECT,("\n"));
4648     /*
4649      * If the event is due to disconnect cmd from the host, only they the target
4650      * would stop trying to connect. Under any other condition, target would
4651      * keep trying to connect.
4652      *
4653      */
4654     if( reason == DISCONNECT_CMD)
4655     {
4656         ar->arConnectPending = FALSE;
4657         if ((!ar->arUserBssFilter) && (ar->arWmiReady)) {
4658             wmi_bssfilter_cmd(ar->arWmi, NONE_BSS_FILTER, 0);
4659         }
4660     } else {
4661         ar->arConnectPending = TRUE;
4662         if (((reason == ASSOC_FAILED) && (protocolReasonStatus == 0x11)) ||
4663             ((reason == ASSOC_FAILED) && (protocolReasonStatus == 0x0) && (reconnect_flag == 1))) {
4664             ar->arConnected = TRUE;
4665             return;
4666         }
4667     }
4668
4669     if ((reason == NO_NETWORK_AVAIL) && (ar->arWmiReady)) 
4670     {
4671         bss_t *pWmiSsidnode = NULL;
4672
4673         /* remove the current associated bssid node */
4674         wmi_free_node (ar->arWmi, bssid);
4675
4676         /*
4677          * In case any other same SSID nodes are present
4678          * remove it, since those nodes also not available now
4679          */
4680         do
4681         {
4682             /*
4683              * Find the nodes based on SSID and remove it
4684              * NOTE :: This case will not work out for Hidden-SSID
4685              */
4686             pWmiSsidnode = wmi_find_Ssidnode (ar->arWmi, ar->arSsid, ar->arSsidLen, FALSE, TRUE);
4687
4688             if (pWmiSsidnode)
4689             {
4690                 wmi_free_node (ar->arWmi, pWmiSsidnode->ni_macaddr);
4691             }
4692
4693         } while (pWmiSsidnode);
4694     }
4695
4696     /* Update connect & link status atomically */
4697     spin_lock_irqsave(&ar->arLock, flags);
4698     ar->arConnected = FALSE;
4699     netif_carrier_off(ar->arNetDev);
4700     spin_unlock_irqrestore(&ar->arLock, flags);
4701
4702     if( (reason != CSERV_DISCONNECT) || (reconnect_flag != 1) ) {
4703         reconnect_flag = 0;
4704     }
4705
4706 #ifdef USER_KEYS
4707     if (reason != CSERV_DISCONNECT)
4708     {
4709         ar->user_savedkeys_stat = USER_SAVEDKEYS_STAT_INIT;
4710         ar->user_key_ctrl      = 0;
4711     }
4712 #endif /* USER_KEYS */
4713
4714     netif_stop_queue(ar->arNetDev);
4715     A_MEMZERO(ar->arBssid, sizeof(ar->arBssid));
4716     ar->arBssChannel = 0;
4717     ar->arBeaconInterval = 0;
4718
4719     ar6000_TxDataCleanup(ar);
4720 }
4721
4722 void
4723 ar6000_regDomain_event(AR_SOFTC_T *ar, A_UINT32 regCode)
4724 {
4725     A_PRINTF("AR6000 Reg Code = 0x%x\n", regCode);
4726     ar->arRegCode = regCode;
4727 }
4728
4729 #ifdef ATH_AR6K_11N_SUPPORT
4730 void
4731 ar6000_aggr_rcv_addba_req_evt(AR_SOFTC_T *ar, WMI_ADDBA_REQ_EVENT *evt)
4732 {
4733     if(evt->status == 0) {
4734         aggr_recv_addba_req_evt(ar->aggr_cntxt, evt->tid, evt->st_seq_no, evt->win_sz);
4735     }
4736 }
4737
4738 void
4739 ar6000_aggr_rcv_addba_resp_evt(AR_SOFTC_T *ar, WMI_ADDBA_RESP_EVENT *evt)
4740 {
4741     A_PRINTF("ADDBA RESP. tid %d status %d, sz %d\n", evt->tid, evt->status, evt->amsdu_sz);
4742     if(evt->status == 0) {
4743     }
4744 }
4745
4746 void
4747 ar6000_aggr_rcv_delba_req_evt(AR_SOFTC_T *ar, WMI_DELBA_EVENT *evt)
4748 {
4749     aggr_recv_delba_req_evt(ar->aggr_cntxt, evt->tid);
4750 }
4751 #endif
4752
4753 void register_pal_cb(ar6k_pal_config_t *palConfig_p)
4754 {
4755   ar6k_pal_config_g = *palConfig_p;
4756 }
4757
4758 void
4759 ar6000_hci_event_rcv_evt(struct ar6_softc *ar, WMI_HCI_EVENT *cmd)
4760 {
4761     void *osbuf = NULL;
4762     A_INT8 i;
4763     A_UINT8 size, *buf;
4764     A_STATUS ret = A_OK;
4765
4766     size = cmd->evt_buf_sz + 4;
4767     osbuf = A_NETBUF_ALLOC(size);
4768     if (osbuf == NULL) {
4769        ret = A_NO_MEMORY;
4770        A_PRINTF("Error in allocating netbuf \n");
4771        return;
4772     }
4773
4774     A_NETBUF_PUT(osbuf, size);
4775     buf = (A_UINT8 *)A_NETBUF_DATA(osbuf);
4776     /* First 2-bytes carry HCI event/ACL data type
4777      * the next 2 are free
4778      */
4779     *((short *)buf) = WMI_HCI_EVENT_EVENTID;
4780     buf += sizeof(int);
4781     A_MEMCPY(buf, cmd->buf, cmd->evt_buf_sz);
4782
4783     if(ar6k_pal_config_g.fpar6k_pal_recv_pkt)
4784     {
4785       /* pass the cmd packet to PAL driver */
4786       if((*ar6k_pal_config_g.fpar6k_pal_recv_pkt)(ar->hcipal_info, osbuf) == TRUE)
4787         return;
4788     }
4789     ar6000_deliver_frames_to_nw_stack(ar->arNetDev, osbuf);
4790     if(loghci) {
4791         A_PRINTF_LOG("HCI Event From PAL <-- \n");
4792         for(i = 0; i < cmd->evt_buf_sz; i++) {
4793            A_PRINTF_LOG("0x%02x ", cmd->buf[i]);
4794            if((i % 10) == 0) {
4795                A_PRINTF_LOG("\n");
4796            }
4797         }
4798         A_PRINTF_LOG("\n");
4799         A_PRINTF_LOG("==================================\n");
4800     }
4801 }
4802
4803 void
4804 ar6000_neighborReport_event(AR_SOFTC_T *ar, int numAps, WMI_NEIGHBOR_INFO *info)
4805 {
4806 #if WIRELESS_EXT >= 18
4807     struct iw_pmkid_cand *pmkcand;
4808 #else /* WIRELESS_EXT >= 18 */
4809     static const char *tag = "PRE-AUTH";
4810     char buf[128];
4811 #endif /* WIRELESS_EXT >= 18 */
4812
4813     union iwreq_data wrqu;
4814     int i;
4815
4816     AR_DEBUG_PRINTF(ATH_DEBUG_WLAN_SCAN,("AR6000 Neighbor Report Event\n"));
4817     for (i=0; i < numAps; info++, i++) {
4818         AR_DEBUG_PRINTF(ATH_DEBUG_WLAN_SCAN,("bssid %2.2x:%2.2x:%2.2x:%2.2x:%2.2x:%2.2x ",
4819             info->bssid[0], info->bssid[1], info->bssid[2],
4820             info->bssid[3], info->bssid[4], info->bssid[5]));
4821         if (info->bssFlags & WMI_PREAUTH_CAPABLE_BSS) {
4822             AR_DEBUG_PRINTF(ATH_DEBUG_WLAN_SCAN,("preauth-cap"));
4823         }
4824         if (info->bssFlags & WMI_PMKID_VALID_BSS) {
4825             AR_DEBUG_PRINTF(ATH_DEBUG_WLAN_SCAN,(" pmkid-valid\n"));
4826             continue;           /* we skip bss if the pmkid is already valid */
4827         }
4828         AR_DEBUG_PRINTF(ATH_DEBUG_WLAN_SCAN,("\n"));
4829         A_MEMZERO(&wrqu, sizeof(wrqu));
4830 #if WIRELESS_EXT >= 18
4831         pmkcand = A_MALLOC_NOWAIT(sizeof(struct iw_pmkid_cand));
4832         A_MEMZERO(pmkcand, sizeof(struct iw_pmkid_cand));
4833         pmkcand->index = i;
4834         pmkcand->flags = info->bssFlags;
4835         A_MEMCPY(pmkcand->bssid.sa_data, info->bssid, ATH_MAC_LEN);
4836         wrqu.data.length = sizeof(struct iw_pmkid_cand);
4837         wireless_send_event(ar->arNetDev, IWEVPMKIDCAND, &wrqu, (char *)pmkcand);
4838         A_FREE(pmkcand);
4839 #else /* WIRELESS_EXT >= 18 */
4840         snprintf(buf, sizeof(buf), "%s%2.2x%2.2x%2.2x%2.2x%2.2x%2.2x%2.2x%2.2x",
4841                  tag,
4842                  info->bssid[0], info->bssid[1], info->bssid[2],
4843                  info->bssid[3], info->bssid[4], info->bssid[5],
4844                  i, info->bssFlags);
4845         wrqu.data.length = strlen(buf);
4846         wireless_send_event(ar->arNetDev, IWEVCUSTOM, &wrqu, buf);
4847 #endif /* WIRELESS_EXT >= 18 */
4848     }
4849 }
4850
4851 void
4852 ar6000_tkip_micerr_event(AR_SOFTC_T *ar, A_UINT8 keyid, A_BOOL ismcast)
4853 {
4854     static const char *tag = "MLME-MICHAELMICFAILURE.indication";
4855     char buf[128];
4856     union iwreq_data wrqu;
4857
4858     /*
4859      * For AP case, keyid will have aid of STA which sent pkt with
4860      * MIC error. Use this aid to get MAC & send it to hostapd.
4861      */
4862     if (ar->arNetworkType == AP_NETWORK) {
4863         sta_t *s = ieee80211_find_conn_for_aid(ar, (keyid >> 2));
4864         if(!s){
4865             A_PRINTF("AP TKIP MIC error received from Invalid aid / STA not found =%d\n", keyid);
4866             return;
4867         }
4868         A_PRINTF("AP TKIP MIC error received from aid=%d\n", keyid);
4869         snprintf(buf,sizeof(buf), "%s addr=%2.2x:%2.2x:%2.2x:%2.2x:%2.2x:%2.2x",
4870             tag, s->mac[0],s->mac[1],s->mac[2],s->mac[3],s->mac[4],s->mac[5]);
4871     } else {
4872
4873 #ifdef ATH6K_CONFIG_CFG80211
4874     ar6k_cfg80211_tkip_micerr_event(ar, keyid, ismcast);
4875 #endif /* ATH6K_CONFIG_CFG80211 */
4876
4877         A_PRINTF("AR6000 TKIP MIC error received for keyid %d %scast\n",
4878              keyid & 0x3, ismcast ? "multi": "uni");
4879         snprintf(buf, sizeof(buf), "%s(keyid=%d %sicast)", tag, keyid & 0x3,
4880              ismcast ? "mult" : "un");
4881     }
4882
4883     memset(&wrqu, 0, sizeof(wrqu));
4884     wrqu.data.length = strlen(buf);
4885     wireless_send_event(ar->arNetDev, IWEVCUSTOM, &wrqu, buf);
4886 }
4887
4888 void
4889 ar6000_scanComplete_event(AR_SOFTC_T *ar, A_STATUS status)
4890 {
4891
4892 #ifdef ATH6K_CONFIG_CFG80211
4893     ar6k_cfg80211_scanComplete_event(ar, status);
4894 #endif /* ATH6K_CONFIG_CFG80211 */
4895
4896     if (!ar->arUserBssFilter) {
4897         wmi_bssfilter_cmd(ar->arWmi, NONE_BSS_FILTER, 0);
4898     }
4899     if (ar->scan_triggered) {
4900         if (status==A_OK) {
4901             union iwreq_data wrqu;
4902             A_MEMZERO(&wrqu, sizeof(wrqu));
4903             wireless_send_event(ar->arNetDev, SIOCGIWSCAN, &wrqu, NULL);
4904         }
4905         ar->scan_triggered = 0;
4906     }
4907
4908     AR_DEBUG_PRINTF(ATH_DEBUG_WLAN_SCAN,( "AR6000 scan complete: %d\n", status));
4909 }
4910
4911 void
4912 ar6000_targetStats_event(AR_SOFTC_T *ar,  A_UINT8 *ptr, A_UINT32 len)
4913 {
4914     A_UINT8 ac;
4915
4916     if(ar->arNetworkType == AP_NETWORK) {
4917         WMI_AP_MODE_STAT *p = (WMI_AP_MODE_STAT *)ptr;
4918         WMI_AP_MODE_STAT *ap = &ar->arAPStats;
4919
4920         if (len < sizeof(*p)) {
4921             return;
4922         }
4923
4924         for(ac=0;ac<AP_MAX_NUM_STA;ac++) {
4925             ap->sta[ac].tx_bytes   += p->sta[ac].tx_bytes;
4926             ap->sta[ac].tx_pkts    += p->sta[ac].tx_pkts;
4927             ap->sta[ac].tx_error   += p->sta[ac].tx_error;
4928             ap->sta[ac].tx_discard += p->sta[ac].tx_discard;
4929             ap->sta[ac].rx_bytes   += p->sta[ac].rx_bytes;
4930             ap->sta[ac].rx_pkts    += p->sta[ac].rx_pkts;
4931             ap->sta[ac].rx_error   += p->sta[ac].rx_error;
4932             ap->sta[ac].rx_discard += p->sta[ac].rx_discard;
4933         }
4934
4935     } else {
4936         WMI_TARGET_STATS *pTarget = (WMI_TARGET_STATS *)ptr;
4937          TARGET_STATS *pStats = &ar->arTargetStats;
4938
4939         if (len < sizeof(*pTarget)) {
4940             return;
4941         }
4942
4943         // Update the RSSI of the connected bss.
4944         if (ar->arConnected) {
4945             bss_t *pConnBss = NULL;
4946
4947             pConnBss = wmi_find_node(ar->arWmi,ar->arBssid);
4948             if (pConnBss)
4949             {
4950                 pConnBss->ni_rssi = pTarget->cservStats.cs_aveBeacon_rssi;
4951                 pConnBss->ni_snr = pTarget->cservStats.cs_aveBeacon_snr;
4952                 wmi_node_return(ar->arWmi, pConnBss);
4953             }
4954         }
4955
4956         AR_DEBUG_PRINTF(ATH_DEBUG_INFO,("AR6000 updating target stats\n"));
4957         pStats->tx_packets          += pTarget->txrxStats.tx_stats.tx_packets;
4958         pStats->tx_bytes            += pTarget->txrxStats.tx_stats.tx_bytes;
4959         pStats->tx_unicast_pkts     += pTarget->txrxStats.tx_stats.tx_unicast_pkts;
4960         pStats->tx_unicast_bytes    += pTarget->txrxStats.tx_stats.tx_unicast_bytes;
4961         pStats->tx_multicast_pkts   += pTarget->txrxStats.tx_stats.tx_multicast_pkts;
4962         pStats->tx_multicast_bytes  += pTarget->txrxStats.tx_stats.tx_multicast_bytes;
4963         pStats->tx_broadcast_pkts   += pTarget->txrxStats.tx_stats.tx_broadcast_pkts;
4964         pStats->tx_broadcast_bytes  += pTarget->txrxStats.tx_stats.tx_broadcast_bytes;
4965         pStats->tx_rts_success_cnt  += pTarget->txrxStats.tx_stats.tx_rts_success_cnt;
4966         for(ac = 0; ac < WMM_NUM_AC; ac++)
4967             pStats->tx_packet_per_ac[ac] += pTarget->txrxStats.tx_stats.tx_packet_per_ac[ac];
4968         pStats->tx_errors           += pTarget->txrxStats.tx_stats.tx_errors;
4969         pStats->tx_failed_cnt       += pTarget->txrxStats.tx_stats.tx_failed_cnt;
4970         pStats->tx_retry_cnt        += pTarget->txrxStats.tx_stats.tx_retry_cnt;
4971         pStats->tx_mult_retry_cnt   += pTarget->txrxStats.tx_stats.tx_mult_retry_cnt;
4972         pStats->tx_rts_fail_cnt     += pTarget->txrxStats.tx_stats.tx_rts_fail_cnt;
4973         pStats->tx_unicast_rate      = wmi_get_rate(pTarget->txrxStats.tx_stats.tx_unicast_rate);
4974
4975         pStats->rx_packets          += pTarget->txrxStats.rx_stats.rx_packets;
4976         pStats->rx_bytes            += pTarget->txrxStats.rx_stats.rx_bytes;
4977         pStats->rx_unicast_pkts     += pTarget->txrxStats.rx_stats.rx_unicast_pkts;
4978         pStats->rx_unicast_bytes    += pTarget->txrxStats.rx_stats.rx_unicast_bytes;
4979         pStats->rx_multicast_pkts   += pTarget->txrxStats.rx_stats.rx_multicast_pkts;
4980         pStats->rx_multicast_bytes  += pTarget->txrxStats.rx_stats.rx_multicast_bytes;
4981         pStats->rx_broadcast_pkts   += pTarget->txrxStats.rx_stats.rx_broadcast_pkts;
4982         pStats->rx_broadcast_bytes  += pTarget->txrxStats.rx_stats.rx_broadcast_bytes;
4983         pStats->rx_fragment_pkt     += pTarget->txrxStats.rx_stats.rx_fragment_pkt;
4984         pStats->rx_errors           += pTarget->txrxStats.rx_stats.rx_errors;
4985         pStats->rx_crcerr           += pTarget->txrxStats.rx_stats.rx_crcerr;
4986         pStats->rx_key_cache_miss   += pTarget->txrxStats.rx_stats.rx_key_cache_miss;
4987         pStats->rx_decrypt_err      += pTarget->txrxStats.rx_stats.rx_decrypt_err;
4988         pStats->rx_duplicate_frames += pTarget->txrxStats.rx_stats.rx_duplicate_frames;
4989         pStats->rx_unicast_rate      = wmi_get_rate(pTarget->txrxStats.rx_stats.rx_unicast_rate);
4990
4991
4992         pStats->tkip_local_mic_failure
4993                                 += pTarget->txrxStats.tkipCcmpStats.tkip_local_mic_failure;
4994         pStats->tkip_counter_measures_invoked
4995                                 += pTarget->txrxStats.tkipCcmpStats.tkip_counter_measures_invoked;
4996         pStats->tkip_replays        += pTarget->txrxStats.tkipCcmpStats.tkip_replays;
4997         pStats->tkip_format_errors  += pTarget->txrxStats.tkipCcmpStats.tkip_format_errors;
4998         pStats->ccmp_format_errors  += pTarget->txrxStats.tkipCcmpStats.ccmp_format_errors;
4999         pStats->ccmp_replays        += pTarget->txrxStats.tkipCcmpStats.ccmp_replays;
5000
5001         pStats->power_save_failure_cnt += pTarget->pmStats.power_save_failure_cnt;
5002         pStats->noise_floor_calibation = pTarget->noise_floor_calibation;
5003
5004         pStats->cs_bmiss_cnt        += pTarget->cservStats.cs_bmiss_cnt;
5005         pStats->cs_lowRssi_cnt      += pTarget->cservStats.cs_lowRssi_cnt;
5006         pStats->cs_connect_cnt      += pTarget->cservStats.cs_connect_cnt;
5007         pStats->cs_disconnect_cnt   += pTarget->cservStats.cs_disconnect_cnt;
5008         pStats->cs_aveBeacon_snr    = pTarget->cservStats.cs_aveBeacon_snr;
5009         pStats->cs_aveBeacon_rssi   = pTarget->cservStats.cs_aveBeacon_rssi;
5010
5011         if (enablerssicompensation) {
5012             pStats->cs_aveBeacon_rssi =
5013                     rssi_compensation_calc(ar, pStats->cs_aveBeacon_rssi);
5014         }
5015         pStats->cs_lastRoam_msec    = pTarget->cservStats.cs_lastRoam_msec;
5016         pStats->cs_snr              = pTarget->cservStats.cs_snr;
5017         pStats->cs_rssi             = pTarget->cservStats.cs_rssi;
5018
5019         pStats->lq_val              = pTarget->lqVal;
5020
5021         pStats->wow_num_pkts_dropped += pTarget->wowStats.wow_num_pkts_dropped;
5022         pStats->wow_num_host_pkt_wakeups += pTarget->wowStats.wow_num_host_pkt_wakeups;
5023         pStats->wow_num_host_event_wakeups += pTarget->wowStats.wow_num_host_event_wakeups;
5024         pStats->wow_num_events_discarded += pTarget->wowStats.wow_num_events_discarded;
5025         pStats->arp_received += pTarget->arpStats.arp_received;
5026         pStats->arp_matched  += pTarget->arpStats.arp_matched;
5027         pStats->arp_replied  += pTarget->arpStats.arp_replied;
5028
5029         if (ar->statsUpdatePending) {
5030             ar->statsUpdatePending = FALSE;
5031             wake_up(&arEvent);
5032         }
5033     }
5034 }
5035
5036 void
5037 ar6000_rssiThreshold_event(AR_SOFTC_T *ar,  WMI_RSSI_THRESHOLD_VAL newThreshold, A_INT16 rssi)
5038 {
5039     USER_RSSI_THOLD userRssiThold;
5040
5041     rssi = rssi + SIGNAL_QUALITY_NOISE_FLOOR;
5042
5043     if (enablerssicompensation) {
5044         rssi = rssi_compensation_calc(ar, rssi);
5045     }
5046
5047     /* Send an event to the app */
5048     userRssiThold.tag = ar->rssi_map[newThreshold].tag;
5049     userRssiThold.rssi = rssi;
5050     A_PRINTF("rssi Threshold range = %d tag = %d  rssi = %d\n", newThreshold,
5051              userRssiThold.tag, userRssiThold.rssi);
5052
5053     ar6000_send_event_to_app(ar, WMI_RSSI_THRESHOLD_EVENTID,(A_UINT8 *)&userRssiThold, sizeof(USER_RSSI_THOLD));
5054 }
5055
5056
5057 void
5058 ar6000_hbChallengeResp_event(AR_SOFTC_T *ar, A_UINT32 cookie, A_UINT32 source)
5059 {
5060     if (source == APP_HB_CHALLENGE) {
5061         /* Report it to the app in case it wants a positive acknowledgement */
5062         ar6000_send_event_to_app(ar, WMIX_HB_CHALLENGE_RESP_EVENTID,
5063                                  (A_UINT8 *)&cookie, sizeof(cookie));
5064     } else {
5065         /* This would ignore the replys that come in after their due time */
5066         if (cookie == ar->arHBChallengeResp.seqNum) {
5067             ar->arHBChallengeResp.outstanding = FALSE;
5068         }
5069     }
5070 }
5071
5072
5073 void
5074 ar6000_reportError_event(AR_SOFTC_T *ar, WMI_TARGET_ERROR_VAL errorVal)
5075 {
5076         static const char * const errString[] = {
5077                 [WMI_TARGET_PM_ERR_FAIL]    "WMI_TARGET_PM_ERR_FAIL",
5078                 [WMI_TARGET_KEY_NOT_FOUND]  "WMI_TARGET_KEY_NOT_FOUND",
5079                 [WMI_TARGET_DECRYPTION_ERR] "WMI_TARGET_DECRYPTION_ERR",
5080                 [WMI_TARGET_BMISS]          "WMI_TARGET_BMISS",
5081                 [WMI_PSDISABLE_NODE_JOIN]   "WMI_PSDISABLE_NODE_JOIN"
5082         };
5083
5084     A_PRINTF("AR6000 Error on Target. Error = 0x%x\n", errorVal);
5085
5086     /* One error is reported at a time, and errorval is a bitmask */
5087     if(errorVal & (errorVal - 1))
5088        return;
5089
5090     A_PRINTF("AR6000 Error type = ");
5091     switch(errorVal)
5092     {
5093         case WMI_TARGET_PM_ERR_FAIL:
5094         case WMI_TARGET_KEY_NOT_FOUND:
5095         case WMI_TARGET_DECRYPTION_ERR:
5096         case WMI_TARGET_BMISS:
5097         case WMI_PSDISABLE_NODE_JOIN:
5098             A_PRINTF("%s\n", errString[errorVal]);
5099             break;
5100         default:
5101             A_PRINTF("INVALID\n");
5102             break;
5103     }
5104
5105 }
5106
5107
5108 void
5109 ar6000_cac_event(AR_SOFTC_T *ar, A_UINT8 ac, A_UINT8 cacIndication,
5110                  A_UINT8 statusCode, A_UINT8 *tspecSuggestion)
5111 {
5112     WMM_TSPEC_IE    *tspecIe;
5113
5114     /*
5115      * This is the TSPEC IE suggestion from AP.
5116      * Suggestion provided by AP under some error
5117      * cases, could be helpful for the host app.
5118      * Check documentation.
5119      */
5120     tspecIe = (WMM_TSPEC_IE *)tspecSuggestion;
5121
5122     /*
5123      * What do we do, if we get TSPEC rejection? One thought
5124      * that comes to mind is implictly delete the pstream...
5125      */
5126     A_PRINTF("AR6000 CAC notification. "
5127                 "AC = %d, cacIndication = 0x%x, statusCode = 0x%x\n",
5128                  ac, cacIndication, statusCode);
5129 }
5130
5131 void
5132 ar6000_channel_change_event(AR_SOFTC_T *ar, A_UINT16 oldChannel,
5133                             A_UINT16 newChannel)
5134 {
5135     A_PRINTF("Channel Change notification\nOld Channel: %d, New Channel: %d\n",
5136              oldChannel, newChannel);
5137 }
5138
5139 #define AR6000_PRINT_BSSID(_pBss)  do {     \
5140         A_PRINTF("%2.2x:%2.2x:%2.2x:%2.2x:%2.2x:%2.2x ",\
5141                  (_pBss)[0],(_pBss)[1],(_pBss)[2],(_pBss)[3],\
5142                  (_pBss)[4],(_pBss)[5]);  \
5143 } while(0)
5144
5145 void
5146 ar6000_roam_tbl_event(AR_SOFTC_T *ar, WMI_TARGET_ROAM_TBL *pTbl)
5147 {
5148     A_UINT8 i;
5149
5150     A_PRINTF("ROAM TABLE NO OF ENTRIES is %d ROAM MODE is %d\n",
5151               pTbl->numEntries, pTbl->roamMode);
5152     for (i= 0; i < pTbl->numEntries; i++) {
5153         A_PRINTF("[%d]bssid %2.2x:%2.2x:%2.2x:%2.2x:%2.2x:%2.2x ", i,
5154             pTbl->bssRoamInfo[i].bssid[0], pTbl->bssRoamInfo[i].bssid[1],
5155             pTbl->bssRoamInfo[i].bssid[2],
5156             pTbl->bssRoamInfo[i].bssid[3],
5157             pTbl->bssRoamInfo[i].bssid[4],
5158             pTbl->bssRoamInfo[i].bssid[5]);
5159         A_PRINTF("RSSI %d RSSIDT %d LAST RSSI %d UTIL %d ROAM_UTIL %d"
5160                  " BIAS %d\n",
5161             pTbl->bssRoamInfo[i].rssi,
5162             pTbl->bssRoamInfo[i].rssidt,
5163             pTbl->bssRoamInfo[i].last_rssi,
5164             pTbl->bssRoamInfo[i].util,
5165             pTbl->bssRoamInfo[i].roam_util,
5166             pTbl->bssRoamInfo[i].bias);
5167     }
5168 }
5169
5170 void
5171 ar6000_wow_list_event(struct ar6_softc *ar, A_UINT8 num_filters, WMI_GET_WOW_LIST_REPLY *wow_reply)
5172 {
5173     A_UINT8 i,j;
5174
5175     /*Each event now contains exactly one filter, see bug 26613*/
5176     A_PRINTF("WOW pattern %d of %d patterns\n", wow_reply->this_filter_num,                 wow_reply->num_filters);
5177     A_PRINTF("wow mode = %s host mode = %s\n",
5178             (wow_reply->wow_mode == 0? "disabled":"enabled"),
5179             (wow_reply->host_mode == 1 ? "awake":"asleep"));
5180
5181
5182     /*If there are no patterns, the reply will only contain generic
5183       WoW information. Pattern information will exist only if there are
5184       patterns present. Bug 26716*/
5185
5186    /* If this event contains pattern information, display it*/
5187     if (wow_reply->this_filter_num) {
5188         i=0;
5189         A_PRINTF("id=%d size=%d offset=%d\n",
5190                     wow_reply->wow_filters[i].wow_filter_id,
5191                     wow_reply->wow_filters[i].wow_filter_size,
5192                     wow_reply->wow_filters[i].wow_filter_offset);
5193        A_PRINTF("wow pattern = ");
5194        for (j=0; j< wow_reply->wow_filters[i].wow_filter_size; j++) {
5195              A_PRINTF("%2.2x",wow_reply->wow_filters[i].wow_filter_pattern[j]);
5196         }
5197
5198         A_PRINTF("\nwow mask = ");
5199         for (j=0; j< wow_reply->wow_filters[i].wow_filter_size; j++) {
5200             A_PRINTF("%2.2x",wow_reply->wow_filters[i].wow_filter_mask[j]);
5201         }
5202         A_PRINTF("\n");
5203     }
5204 }
5205
5206 /*
5207  * Report the Roaming related data collected on the target
5208  */
5209 void
5210 ar6000_display_roam_time(WMI_TARGET_ROAM_TIME *p)
5211 {
5212     A_PRINTF("Disconnect Data : BSSID: ");
5213     AR6000_PRINT_BSSID(p->disassoc_bssid);
5214     A_PRINTF(" RSSI %d DISASSOC Time %d NO_TXRX_TIME %d\n",
5215              p->disassoc_bss_rssi,p->disassoc_time,
5216              p->no_txrx_time);
5217     A_PRINTF("Connect Data: BSSID: ");
5218     AR6000_PRINT_BSSID(p->assoc_bssid);
5219     A_PRINTF(" RSSI %d ASSOC Time %d TXRX_TIME %d\n",
5220              p->assoc_bss_rssi,p->assoc_time,
5221              p->allow_txrx_time);
5222 }
5223
5224 void
5225 ar6000_roam_data_event(AR_SOFTC_T *ar, WMI_TARGET_ROAM_DATA *p)
5226 {
5227     switch (p->roamDataType) {
5228         case ROAM_DATA_TIME:
5229             ar6000_display_roam_time(&p->u.roamTime);
5230             break;
5231         default:
5232             break;
5233     }
5234 }
5235
5236 void
5237 ar6000_bssInfo_event_rx(AR_SOFTC_T *ar, A_UINT8 *datap, int len)
5238 {
5239     struct sk_buff *skb;
5240     WMI_BSS_INFO_HDR *bih = (WMI_BSS_INFO_HDR *)datap;
5241
5242
5243     if (!ar->arMgmtFilter) {
5244         return;
5245     }
5246     if (((ar->arMgmtFilter & IEEE80211_FILTER_TYPE_BEACON) &&
5247         (bih->frameType != BEACON_FTYPE))  ||
5248         ((ar->arMgmtFilter & IEEE80211_FILTER_TYPE_PROBE_RESP) &&
5249         (bih->frameType != PROBERESP_FTYPE)))
5250     {
5251         return;
5252     }
5253
5254     if ((skb = A_NETBUF_ALLOC_RAW(len)) != NULL) {
5255
5256         A_NETBUF_PUT(skb, len);
5257         A_MEMCPY(A_NETBUF_DATA(skb), datap, len);
5258         skb->dev = ar->arNetDev;
5259         A_MEMCPY(skb_mac_header(skb), A_NETBUF_DATA(skb), 6);
5260         skb->ip_summed = CHECKSUM_NONE;
5261         skb->pkt_type = PACKET_OTHERHOST;
5262         skb->protocol = __constant_htons(0x0019);
5263         netif_rx(skb);
5264     }
5265 }
5266
5267 A_UINT32 wmiSendCmdNum;
5268
5269 A_STATUS
5270 ar6000_control_tx(void *devt, void *osbuf, HTC_ENDPOINT_ID eid)
5271 {
5272     AR_SOFTC_T       *ar = (AR_SOFTC_T *)devt;
5273     A_STATUS         status = A_OK;
5274     struct ar_cookie *cookie = NULL;
5275     int i;
5276 #ifdef CONFIG_PM
5277     if (ar->arWowState != WLAN_WOW_STATE_NONE) {
5278         A_NETBUF_FREE(osbuf);
5279         return A_EACCES;
5280     }
5281 #endif /* CONFIG_PM */
5282         /* take lock to protect ar6000_alloc_cookie() */
5283     AR6000_SPIN_LOCK(&ar->arLock, 0);
5284
5285     do {
5286
5287         AR_DEBUG_PRINTF(ATH_DEBUG_WLAN_TX,("ar_contrstatus = ol_tx: skb=0x%lx, len=0x%x eid =%d\n",
5288                          (unsigned long)osbuf, A_NETBUF_LEN(osbuf), eid));
5289
5290         if (ar->arWMIControlEpFull && (eid == ar->arControlEp)) {
5291                 /* control endpoint is full, don't allocate resources, we
5292                  * are just going to drop this packet */
5293             cookie = NULL;
5294             AR_DEBUG_PRINTF(ATH_DEBUG_ERR,(" WMI Control EP full, dropping packet : 0x%lX, len:%d \n",
5295                     (unsigned long)osbuf, A_NETBUF_LEN(osbuf)));
5296         } else {
5297             cookie = ar6000_alloc_cookie(ar);
5298         }
5299
5300         if (cookie == NULL) {
5301             status = A_NO_MEMORY;
5302             break;
5303         }
5304
5305         if(logWmiRawMsgs) {
5306             A_PRINTF("WMI cmd send, msgNo %d :", wmiSendCmdNum);
5307             for(i = 0; i < a_netbuf_to_len(osbuf); i++)
5308                 A_PRINTF("%x ", ((A_UINT8 *)a_netbuf_to_data(osbuf))[i]);
5309             A_PRINTF("\n");
5310         }
5311
5312         wmiSendCmdNum++;
5313
5314     } while (FALSE);
5315
5316     if (cookie != NULL) {
5317             /* got a structure to send it out on */
5318         ar->arTxPending[eid]++;
5319
5320         if (eid != ar->arControlEp) {
5321             ar->arTotalTxDataPending++;
5322         }
5323     }
5324
5325     AR6000_SPIN_UNLOCK(&ar->arLock, 0);
5326
5327     if (cookie != NULL) {
5328         cookie->arc_bp[0] = (unsigned long)osbuf;
5329         cookie->arc_bp[1] = 0;
5330         SET_HTC_PACKET_INFO_TX(&cookie->HtcPkt,
5331                                cookie,
5332                                A_NETBUF_DATA(osbuf),
5333                                A_NETBUF_LEN(osbuf),
5334                                eid,
5335                                AR6K_CONTROL_PKT_TAG);
5336             /* this interface is asynchronous, if there is an error, cleanup will happen in the
5337              * TX completion callback */
5338         HTCSendPkt(ar->arHtcTarget, &cookie->HtcPkt);
5339         status = A_OK;
5340     }
5341
5342     if (status != A_OK) {
5343         A_NETBUF_FREE(osbuf);
5344     }
5345     return status;
5346 }
5347
5348 /* indicate tx activity or inactivity on a WMI stream */
5349 void ar6000_indicate_tx_activity(void *devt, A_UINT8 TrafficClass, A_BOOL Active)
5350 {
5351     AR_SOFTC_T  *ar = (AR_SOFTC_T *)devt;
5352     HTC_ENDPOINT_ID eid ;
5353     int i;
5354
5355     if (ar->arWmiEnabled) {
5356         eid = arAc2EndpointID(ar, TrafficClass);
5357
5358         AR6000_SPIN_LOCK(&ar->arLock, 0);
5359
5360         ar->arAcStreamActive[TrafficClass] = Active;
5361
5362         if (Active) {
5363             /* when a stream goes active, keep track of the active stream with the highest priority */
5364
5365             if (ar->arAcStreamPriMap[TrafficClass] > ar->arHiAcStreamActivePri) {
5366                     /* set the new highest active priority */
5367                 ar->arHiAcStreamActivePri = ar->arAcStreamPriMap[TrafficClass];
5368             }
5369
5370         } else {
5371             /* when a stream goes inactive, we may have to search for the next active stream
5372              * that is the highest priority */
5373
5374             if (ar->arHiAcStreamActivePri == ar->arAcStreamPriMap[TrafficClass]) {
5375
5376                 /* the highest priority stream just went inactive */
5377
5378                     /* reset and search for the "next" highest "active" priority stream */
5379                 ar->arHiAcStreamActivePri = 0;
5380                 for (i = 0; i < WMM_NUM_AC; i++) {
5381                     if (ar->arAcStreamActive[i]) {
5382                         if (ar->arAcStreamPriMap[i] > ar->arHiAcStreamActivePri) {
5383                             /* set the new highest active priority */
5384                             ar->arHiAcStreamActivePri = ar->arAcStreamPriMap[i];
5385                         }
5386                     }
5387                 }
5388             }
5389         }
5390
5391         AR6000_SPIN_UNLOCK(&ar->arLock, 0);
5392
5393     } else {
5394             /* for mbox ping testing, the traffic class is mapped directly as a stream ID,
5395              * see handling of AR6000_XIOCTL_TRAFFIC_ACTIVITY_CHANGE in ioctl.c
5396              * convert the stream ID to a endpoint */
5397         eid = arAc2EndpointID(ar, TrafficClass);
5398     }
5399
5400         /* notify HTC, this may cause credit distribution changes */
5401
5402     HTCIndicateActivityChange(ar->arHtcTarget,
5403                               eid,
5404                               Active);
5405
5406 }
5407
5408 void
5409 ar6000_btcoex_config_event(struct ar6_softc *ar,  A_UINT8 *ptr, A_UINT32 len)
5410 {
5411
5412     WMI_BTCOEX_CONFIG_EVENT *pBtcoexConfig = (WMI_BTCOEX_CONFIG_EVENT *)ptr;
5413     WMI_BTCOEX_CONFIG_EVENT *pArbtcoexConfig =&ar->arBtcoexConfig;
5414
5415     AR_DEBUG_PRINTF(ATH_DEBUG_INFO,("AR6000 BTCOEX CONFIG EVENT \n"));
5416
5417     A_PRINTF("received config event\n");
5418     pArbtcoexConfig->btProfileType = pBtcoexConfig->btProfileType;
5419     pArbtcoexConfig->linkId = pBtcoexConfig->linkId;
5420
5421     switch (pBtcoexConfig->btProfileType) {
5422         case WMI_BTCOEX_BT_PROFILE_SCO:
5423             A_MEMCPY(&pArbtcoexConfig->info.scoConfigCmd, &pBtcoexConfig->info.scoConfigCmd,
5424                                         sizeof(WMI_SET_BTCOEX_SCO_CONFIG_CMD));
5425             break;
5426         case WMI_BTCOEX_BT_PROFILE_A2DP:
5427             A_MEMCPY(&pArbtcoexConfig->info.a2dpConfigCmd, &pBtcoexConfig->info.a2dpConfigCmd,
5428                                         sizeof(WMI_SET_BTCOEX_A2DP_CONFIG_CMD));
5429             break;
5430         case WMI_BTCOEX_BT_PROFILE_ACLCOEX:
5431             A_MEMCPY(&pArbtcoexConfig->info.aclcoexConfig, &pBtcoexConfig->info.aclcoexConfig,
5432                                         sizeof(WMI_SET_BTCOEX_ACLCOEX_CONFIG_CMD));
5433             break;
5434         case WMI_BTCOEX_BT_PROFILE_INQUIRY_PAGE:
5435            A_MEMCPY(&pArbtcoexConfig->info.btinquiryPageConfigCmd, &pBtcoexConfig->info.btinquiryPageConfigCmd,
5436                                         sizeof(WMI_SET_BTCOEX_ACLCOEX_CONFIG_CMD));
5437             break;
5438     }
5439     if (ar->statsUpdatePending) {
5440          ar->statsUpdatePending = FALSE;
5441           wake_up(&arEvent);
5442     }
5443 }
5444
5445 void
5446 ar6000_btcoex_stats_event(struct ar6_softc *ar,  A_UINT8 *ptr, A_UINT32 len)
5447 {
5448     WMI_BTCOEX_STATS_EVENT *pBtcoexStats = (WMI_BTCOEX_STATS_EVENT *)ptr;
5449
5450     AR_DEBUG_PRINTF(ATH_DEBUG_INFO,("AR6000 BTCOEX CONFIG EVENT \n"));
5451
5452     A_MEMCPY(&ar->arBtcoexStats, pBtcoexStats, sizeof(WMI_BTCOEX_STATS_EVENT));
5453
5454     if (ar->statsUpdatePending) {
5455          ar->statsUpdatePending = FALSE;
5456         wake_up(&arEvent);
5457     }
5458
5459 }
5460 module_init(ar6000_init_module);
5461 module_exit(ar6000_cleanup_module);
5462
5463 /* Init cookie queue */
5464 static void
5465 ar6000_cookie_init(AR_SOFTC_T *ar)
5466 {
5467     A_UINT32    i;
5468
5469     ar->arCookieList = NULL;
5470     ar->arCookieCount = 0;
5471
5472     A_MEMZERO(s_ar_cookie_mem, sizeof(s_ar_cookie_mem));
5473
5474     for (i = 0; i < MAX_COOKIE_NUM; i++) {
5475         ar6000_free_cookie(ar, &s_ar_cookie_mem[i]);
5476     }
5477 }
5478
5479 /* cleanup cookie queue */
5480 static void
5481 ar6000_cookie_cleanup(AR_SOFTC_T *ar)
5482 {
5483     /* It is gone .... */
5484     ar->arCookieList = NULL;
5485     ar->arCookieCount = 0;
5486 }
5487
5488 /* Init cookie queue */
5489 static void
5490 ar6000_free_cookie(AR_SOFTC_T *ar, struct ar_cookie * cookie)
5491 {
5492     /* Insert first */
5493     A_ASSERT(ar != NULL);
5494     A_ASSERT(cookie != NULL);
5495
5496     cookie->arc_list_next = ar->arCookieList;
5497     ar->arCookieList = cookie;
5498     ar->arCookieCount++;
5499 }
5500
5501 /* cleanup cookie queue */
5502 static struct ar_cookie *
5503 ar6000_alloc_cookie(AR_SOFTC_T  *ar)
5504 {
5505     struct ar_cookie   *cookie;
5506
5507     cookie = ar->arCookieList;
5508     if(cookie != NULL)
5509     {
5510         ar->arCookieList = cookie->arc_list_next;
5511         ar->arCookieCount--;
5512     }
5513
5514     return cookie;
5515 }
5516
5517 #ifdef SEND_EVENT_TO_APP
5518 /*
5519  * This function is used to send event which come from taget to
5520  * the application. The buf which send to application is include
5521  * the event ID and event content.
5522  */
5523 #define EVENT_ID_LEN   2
5524 void ar6000_send_event_to_app(AR_SOFTC_T *ar, A_UINT16 eventId,
5525                               A_UINT8 *datap, int len)
5526 {
5527
5528 #if (WIRELESS_EXT >= 15)
5529
5530 /* note: IWEVCUSTOM only exists in wireless extensions after version 15 */
5531
5532     char *buf;
5533     A_UINT16 size;
5534     union iwreq_data wrqu;
5535
5536     size = len + EVENT_ID_LEN;
5537
5538     if (size > IW_CUSTOM_MAX) {
5539         AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("WMI event ID : 0x%4.4X, len = %d too big for IWEVCUSTOM (max=%d) \n",
5540                 eventId, size, IW_CUSTOM_MAX));
5541         return;
5542     }
5543
5544     buf = A_MALLOC_NOWAIT(size);
5545     if (NULL == buf){
5546         AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("%s: failed to allocate %d bytes\n", __func__, size));
5547         return;
5548     }
5549
5550     A_MEMZERO(buf, size);
5551     A_MEMCPY(buf, &eventId, EVENT_ID_LEN);
5552     A_MEMCPY(buf+EVENT_ID_LEN, datap, len);
5553
5554     //AR_DEBUG_PRINTF(ATH_DEBUG_INFO,("event ID = %d,len = %d\n",*(A_UINT16*)buf, size));
5555     A_MEMZERO(&wrqu, sizeof(wrqu));
5556     wrqu.data.length = size;
5557     wireless_send_event(ar->arNetDev, IWEVCUSTOM, &wrqu, buf);
5558     A_FREE(buf);
5559 #endif
5560
5561
5562 }
5563
5564 /*
5565  * This function is used to send events larger than 256 bytes
5566  * to the application. The buf which is sent to application
5567  * includes the event ID and event content.
5568  */
5569 void ar6000_send_generic_event_to_app(AR_SOFTC_T *ar, A_UINT16 eventId,
5570                                       A_UINT8 *datap, int len)
5571 {
5572
5573 #if (WIRELESS_EXT >= 18)
5574
5575 /* IWEVGENIE exists in wireless extensions version 18 onwards */
5576
5577     char *buf;
5578     A_UINT16 size;
5579     union iwreq_data wrqu;
5580
5581     size = len + EVENT_ID_LEN;
5582
5583     if (size > IW_GENERIC_IE_MAX) {
5584         AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("WMI event ID : 0x%4.4X, len = %d too big for IWEVGENIE (max=%d) \n",
5585                         eventId, size, IW_GENERIC_IE_MAX));
5586         return;
5587     }
5588
5589     buf = A_MALLOC_NOWAIT(size);
5590     if (NULL == buf){
5591         AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("%s: failed to allocate %d bytes\n", __func__, size));
5592         return;
5593     }
5594
5595     A_MEMZERO(buf, size);
5596     A_MEMCPY(buf, &eventId, EVENT_ID_LEN);
5597     A_MEMCPY(buf+EVENT_ID_LEN, datap, len);
5598
5599     A_MEMZERO(&wrqu, sizeof(wrqu));
5600     wrqu.data.length = size;
5601     wireless_send_event(ar->arNetDev, IWEVGENIE, &wrqu, buf);
5602
5603     A_FREE(buf);
5604
5605 #endif /* (WIRELESS_EXT >= 18) */
5606
5607 }
5608 #endif /* SEND_EVENT_TO_APP */
5609
5610
5611 void
5612 ar6000_tx_retry_err_event(void *devt)
5613 {
5614     AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("Tx retries reach maximum!\n"));
5615 }
5616
5617 void
5618 ar6000_snrThresholdEvent_rx(void *devt, WMI_SNR_THRESHOLD_VAL newThreshold, A_UINT8 snr)
5619 {
5620     WMI_SNR_THRESHOLD_EVENT event;
5621     AR_SOFTC_T *ar = (AR_SOFTC_T *)devt;
5622
5623     event.range = newThreshold;
5624     event.snr = snr;
5625
5626     ar6000_send_event_to_app(ar, WMI_SNR_THRESHOLD_EVENTID, (A_UINT8 *)&event,
5627                              sizeof(WMI_SNR_THRESHOLD_EVENT));
5628 }
5629
5630 void
5631 ar6000_lqThresholdEvent_rx(void *devt, WMI_LQ_THRESHOLD_VAL newThreshold, A_UINT8 lq)
5632 {
5633     AR_DEBUG_PRINTF(ATH_DEBUG_INFO,("lq threshold range %d, lq %d\n", newThreshold, lq));
5634 }
5635
5636
5637
5638 A_UINT32
5639 a_copy_to_user(void *to, const void *from, A_UINT32 n)
5640 {
5641     return(copy_to_user(to, from, n));
5642 }
5643
5644 A_UINT32
5645 a_copy_from_user(void *to, const void *from, A_UINT32 n)
5646 {
5647     return(copy_from_user(to, from, n));
5648 }
5649
5650
5651 A_STATUS
5652 ar6000_get_driver_cfg(struct net_device *dev,
5653                         A_UINT16 cfgParam,
5654                         void *result)
5655 {
5656
5657     A_STATUS    ret = 0;
5658
5659     switch(cfgParam)
5660     {
5661         case AR6000_DRIVER_CFG_GET_WLANNODECACHING:
5662            *((A_UINT32 *)result) = wlanNodeCaching;
5663            break;
5664         case AR6000_DRIVER_CFG_LOG_RAW_WMI_MSGS:
5665            *((A_UINT32 *)result) = logWmiRawMsgs;
5666             break;
5667         default:
5668            ret = EINVAL;
5669            break;
5670     }
5671
5672     return ret;
5673 }
5674
5675 void
5676 ar6000_keepalive_rx(void *devt, A_UINT8 configured)
5677 {
5678     AR_SOFTC_T *ar = (AR_SOFTC_T *)devt;
5679
5680     ar->arKeepaliveConfigured = configured;
5681     wake_up(&arEvent);
5682 }
5683
5684 void
5685 ar6000_pmkid_list_event(void *devt, A_UINT8 numPMKID, WMI_PMKID *pmkidList,
5686                         A_UINT8 *bssidList)
5687 {
5688     A_UINT8 i, j;
5689
5690     A_PRINTF("Number of Cached PMKIDs is %d\n", numPMKID);
5691
5692     for (i = 0; i < numPMKID; i++) {
5693         A_PRINTF("\nBSSID %d ", i);
5694             for (j = 0; j < ATH_MAC_LEN; j++) {
5695                 A_PRINTF("%2.2x", bssidList[j]);
5696             }
5697         bssidList += (ATH_MAC_LEN + WMI_PMKID_LEN);
5698         A_PRINTF("\nPMKID %d ", i);
5699             for (j = 0; j < WMI_PMKID_LEN; j++) {
5700                 A_PRINTF("%2.2x", pmkidList->pmkid[j]);
5701             }
5702         pmkidList = (WMI_PMKID *)((A_UINT8 *)pmkidList + ATH_MAC_LEN +
5703                                   WMI_PMKID_LEN);
5704     }
5705 }
5706
5707 void ar6000_pspoll_event(AR_SOFTC_T *ar,A_UINT8 aid)
5708 {
5709     sta_t *conn=NULL;
5710     A_BOOL isPsqEmpty = FALSE;
5711
5712     conn = ieee80211_find_conn_for_aid(ar, aid);
5713
5714     /* If the PS q for this STA is not empty, dequeue and send a pkt from
5715      * the head of the q. Also update the More data bit in the WMI_DATA_HDR
5716      * if there are more pkts for this STA in the PS q. If there are no more
5717      * pkts for this STA, update the PVB for this STA.
5718      */
5719     A_MUTEX_LOCK(&conn->psqLock);
5720     isPsqEmpty  = A_NETBUF_QUEUE_EMPTY(&conn->psq);
5721     A_MUTEX_UNLOCK(&conn->psqLock);
5722
5723     if (isPsqEmpty) {
5724         /* TODO:No buffered pkts for this STA. Send out a NULL data frame */
5725     } else {
5726         struct sk_buff *skb = NULL;
5727
5728         A_MUTEX_LOCK(&conn->psqLock);
5729         skb = A_NETBUF_DEQUEUE(&conn->psq);
5730         A_MUTEX_UNLOCK(&conn->psqLock);
5731         /* Set the STA flag to PSPolled, so that the frame will go out */
5732         STA_SET_PS_POLLED(conn);
5733         ar6000_data_tx(skb, ar->arNetDev);
5734         STA_CLR_PS_POLLED(conn);
5735
5736         /* Clear the PVB for this STA if the queue has become empty */
5737         A_MUTEX_LOCK(&conn->psqLock);
5738         isPsqEmpty  = A_NETBUF_QUEUE_EMPTY(&conn->psq);
5739         A_MUTEX_UNLOCK(&conn->psqLock);
5740
5741         if (isPsqEmpty) {
5742             wmi_set_pvb_cmd(ar->arWmi, conn->aid, 0);
5743         }
5744     }
5745 }
5746
5747 void ar6000_dtimexpiry_event(AR_SOFTC_T *ar)
5748 {
5749     A_BOOL isMcastQueued = FALSE;
5750     struct sk_buff *skb = NULL;
5751
5752     /* If there are no associated STAs, ignore the DTIM expiry event.
5753      * There can be potential race conditions where the last associated
5754      * STA may disconnect & before the host could clear the 'Indicate DTIM'
5755      * request to the firmware, the firmware would have just indicated a DTIM
5756      * expiry event. The race is between 'clear DTIM expiry cmd' going
5757      * from the host to the firmware & the DTIM expiry event happening from
5758      * the firmware to the host.
5759      */
5760     if (ar->sta_list_index == 0) {
5761         return;
5762     }
5763
5764     A_MUTEX_LOCK(&ar->mcastpsqLock);
5765     isMcastQueued = A_NETBUF_QUEUE_EMPTY(&ar->mcastpsq);
5766     A_MUTEX_UNLOCK(&ar->mcastpsqLock);
5767
5768     A_ASSERT(isMcastQueued == FALSE);
5769
5770     /* Flush the mcast psq to the target */
5771     /* Set the STA flag to DTIMExpired, so that the frame will go out */
5772     ar->DTIMExpired = TRUE;
5773
5774     A_MUTEX_LOCK(&ar->mcastpsqLock);
5775     while (!A_NETBUF_QUEUE_EMPTY(&ar->mcastpsq)) {
5776         skb = A_NETBUF_DEQUEUE(&ar->mcastpsq);
5777         A_MUTEX_UNLOCK(&ar->mcastpsqLock);
5778
5779         ar6000_data_tx(skb, ar->arNetDev);
5780
5781         A_MUTEX_LOCK(&ar->mcastpsqLock);
5782     }
5783     A_MUTEX_UNLOCK(&ar->mcastpsqLock);
5784
5785     /* Reset the DTIMExpired flag back to 0 */
5786     ar->DTIMExpired = FALSE;
5787
5788     /* Clear the LSB of the BitMapCtl field of the TIM IE */
5789     wmi_set_pvb_cmd(ar->arWmi, MCAST_AID, 0);
5790 }
5791
5792 void
5793 read_rssi_compensation_param(AR_SOFTC_T *ar)
5794 {
5795     A_UINT8 *cust_data_ptr;
5796
5797 //#define RSSICOMPENSATION_PRINT
5798
5799 #ifdef RSSICOMPENSATION_PRINT
5800     A_INT16 i;
5801     cust_data_ptr = ar6000_get_cust_data_buffer(ar->arTargetType);
5802     for (i=0; i<16; i++) {
5803         A_PRINTF("cust_data_%d = %x \n", i, *(A_UINT8 *)cust_data_ptr);
5804         cust_data_ptr += 1;
5805     }
5806 #endif
5807
5808     cust_data_ptr = ar6000_get_cust_data_buffer(ar->arTargetType);
5809
5810     rssi_compensation_param.customerID = *(A_UINT16 *)cust_data_ptr & 0xffff;
5811     rssi_compensation_param.enable = *(A_UINT16 *)(cust_data_ptr+2) & 0xffff;
5812     rssi_compensation_param.bg_param_a = *(A_UINT16 *)(cust_data_ptr+4) & 0xffff;
5813     rssi_compensation_param.bg_param_b = *(A_UINT16 *)(cust_data_ptr+6) & 0xffff;
5814     rssi_compensation_param.a_param_a = *(A_UINT16 *)(cust_data_ptr+8) & 0xffff;
5815     rssi_compensation_param.a_param_b = *(A_UINT16 *)(cust_data_ptr+10) &0xffff;
5816     rssi_compensation_param.reserved = *(A_UINT32 *)(cust_data_ptr+12);
5817
5818 #ifdef RSSICOMPENSATION_PRINT
5819     A_PRINTF("customerID = 0x%x \n", rssi_compensation_param.customerID);
5820     A_PRINTF("enable = 0x%x \n", rssi_compensation_param.enable);
5821     A_PRINTF("bg_param_a = 0x%x and %d \n", rssi_compensation_param.bg_param_a, rssi_compensation_param.bg_param_a);
5822     A_PRINTF("bg_param_b = 0x%x and %d \n", rssi_compensation_param.bg_param_b, rssi_compensation_param.bg_param_b);
5823     A_PRINTF("a_param_a = 0x%x and %d \n", rssi_compensation_param.a_param_a, rssi_compensation_param.a_param_a);
5824     A_PRINTF("a_param_b = 0x%x and %d \n", rssi_compensation_param.a_param_b, rssi_compensation_param.a_param_b);
5825     A_PRINTF("Last 4 bytes = 0x%x \n", rssi_compensation_param.reserved);
5826 #endif
5827
5828     if (rssi_compensation_param.enable != 0x1) {
5829         rssi_compensation_param.enable = 0;
5830     }
5831
5832    return;
5833 }
5834
5835 A_INT32
5836 rssi_compensation_calc_tcmd(A_UINT32 freq, A_INT32 rssi, A_UINT32 totalPkt)
5837 {
5838
5839     if (freq > 5000)
5840     {
5841         if (rssi_compensation_param.enable)
5842         {
5843             AR_DEBUG_PRINTF(ATH_DEBUG_INFO, (">>> 11a\n"));
5844             AR_DEBUG_PRINTF(ATH_DEBUG_INFO, ("rssi before compensation  = %d, totalPkt = %d\n", rssi,totalPkt));
5845             rssi = rssi * rssi_compensation_param.a_param_a + totalPkt * rssi_compensation_param.a_param_b;
5846             rssi = (rssi-50) /100;
5847             AR_DEBUG_PRINTF(ATH_DEBUG_INFO, ("rssi after compensation = %d\n", rssi));
5848         }
5849     }
5850     else
5851     {
5852         if (rssi_compensation_param.enable)
5853         {
5854             AR_DEBUG_PRINTF(ATH_DEBUG_INFO, (">>> 11bg\n"));
5855             AR_DEBUG_PRINTF(ATH_DEBUG_INFO, ("rssi before compensation  = %d, totalPkt = %d\n", rssi,totalPkt));
5856             rssi = rssi * rssi_compensation_param.bg_param_a + totalPkt * rssi_compensation_param.bg_param_b;
5857             rssi = (rssi-50) /100;
5858             AR_DEBUG_PRINTF(ATH_DEBUG_INFO, ("rssi after compensation = %d\n", rssi));
5859         }
5860     }
5861
5862     return rssi;
5863 }
5864
5865 A_INT16
5866 rssi_compensation_calc(AR_SOFTC_T *ar, A_INT16 rssi)
5867 {
5868     if (ar->arBssChannel > 5000)
5869     {
5870         if (rssi_compensation_param.enable)
5871         {
5872             AR_DEBUG_PRINTF(ATH_DEBUG_INFO, (">>> 11a\n"));
5873             AR_DEBUG_PRINTF(ATH_DEBUG_INFO, ("rssi before compensation  = %d\n", rssi));
5874             rssi = rssi * rssi_compensation_param.a_param_a + rssi_compensation_param.a_param_b;
5875             rssi = (rssi-50) /100;
5876             AR_DEBUG_PRINTF(ATH_DEBUG_INFO, ("rssi after compensation = %d\n", rssi));
5877         }
5878     }
5879     else
5880     {
5881         if (rssi_compensation_param.enable)
5882         {
5883             AR_DEBUG_PRINTF(ATH_DEBUG_INFO, (">>> 11bg\n"));
5884             AR_DEBUG_PRINTF(ATH_DEBUG_INFO, ("rssi before compensation  = %d\n", rssi));
5885             rssi = rssi * rssi_compensation_param.bg_param_a + rssi_compensation_param.bg_param_b;
5886             rssi = (rssi-50) /100;
5887             AR_DEBUG_PRINTF(ATH_DEBUG_INFO, ("rssi after compensation = %d\n", rssi));
5888         }
5889     }
5890
5891     return rssi;
5892 }
5893
5894 A_INT16
5895 rssi_compensation_reverse_calc(AR_SOFTC_T *ar, A_INT16 rssi, A_BOOL Above)
5896 {
5897     A_INT16 i;
5898
5899     if (ar->arBssChannel > 5000)
5900     {
5901         if (rssi_compensation_param.enable)
5902         {
5903             AR_DEBUG_PRINTF(ATH_DEBUG_INFO, (">>> 11a\n"));
5904             AR_DEBUG_PRINTF(ATH_DEBUG_INFO, ("rssi before rev compensation  = %d\n", rssi));
5905             rssi = rssi * 100;
5906             rssi = (rssi - rssi_compensation_param.a_param_b) / rssi_compensation_param.a_param_a;
5907             AR_DEBUG_PRINTF(ATH_DEBUG_INFO, ("rssi after rev compensation = %d\n", rssi));
5908         }
5909     }
5910     else
5911     {
5912         if (rssi_compensation_param.enable)
5913         {
5914             AR_DEBUG_PRINTF(ATH_DEBUG_INFO, (">>> 11bg\n"));
5915             AR_DEBUG_PRINTF(ATH_DEBUG_INFO, ("rssi before rev compensation  = %d\n", rssi));
5916
5917             if (Above) {
5918                 for (i=95; i>=0; i--) {
5919                     if (rssi <=  rssi_compensation_table[i]) {
5920                         rssi = 0 - i;
5921                         break;
5922                     }
5923                 }
5924             } else {
5925                 for (i=0; i<=95; i++) {
5926                     if (rssi >=  rssi_compensation_table[i]) {
5927                         rssi = 0 - i;
5928                         break;
5929                     }
5930                 }
5931             }
5932             AR_DEBUG_PRINTF(ATH_DEBUG_INFO, ("rssi after rev compensation = %d\n", rssi));
5933         }
5934     }
5935
5936     return rssi;
5937 }
5938
5939 #ifdef WAPI_ENABLE
5940 void ap_wapi_rekey_event(AR_SOFTC_T *ar, A_UINT8 type, A_UINT8 *mac)
5941 {
5942     union iwreq_data wrqu;
5943     A_CHAR buf[20];
5944
5945     A_MEMZERO(buf, sizeof(buf));
5946
5947     strcpy(buf, "WAPI_REKEY");
5948     buf[10] = type;
5949     A_MEMCPY(&buf[11], mac, ATH_MAC_LEN);
5950
5951     A_MEMZERO(&wrqu, sizeof(wrqu));
5952     wrqu.data.length = 10+1+ATH_MAC_LEN;
5953     wireless_send_event(ar->arNetDev, IWEVCUSTOM, &wrqu, buf);
5954
5955     A_PRINTF("WAPI REKEY - %d - %02x:%02x\n", type, mac[4], mac[5]);
5956 }
5957 #endif
5958
5959 #ifdef USER_KEYS
5960 static A_STATUS
5961
5962 ar6000_reinstall_keys(AR_SOFTC_T *ar, A_UINT8 key_op_ctrl)
5963 {
5964     A_STATUS status = A_OK;
5965     struct ieee80211req_key *uik = &ar->user_saved_keys.ucast_ik;
5966     struct ieee80211req_key *bik = &ar->user_saved_keys.bcast_ik;
5967     CRYPTO_TYPE  keyType = ar->user_saved_keys.keyType;
5968
5969     if (IEEE80211_CIPHER_CCKM_KRK != uik->ik_type) {
5970         if (NONE_CRYPT == keyType) {
5971             goto _reinstall_keys_out;
5972         }
5973
5974         if (uik->ik_keylen) {
5975             status = wmi_addKey_cmd(ar->arWmi, uik->ik_keyix,
5976                     ar->user_saved_keys.keyType, PAIRWISE_USAGE,
5977                     uik->ik_keylen, (A_UINT8 *)&uik->ik_keyrsc,
5978                     uik->ik_keydata, key_op_ctrl, uik->ik_macaddr, SYNC_BEFORE_WMIFLAG);
5979         }
5980
5981     } else {
5982         status = wmi_add_krk_cmd(ar->arWmi, uik->ik_keydata);
5983     }
5984
5985     if (IEEE80211_CIPHER_CCKM_KRK != bik->ik_type) {
5986         if (NONE_CRYPT == keyType) {
5987             goto _reinstall_keys_out;
5988         }
5989
5990         if (bik->ik_keylen) {
5991             status = wmi_addKey_cmd(ar->arWmi, bik->ik_keyix,
5992                     ar->user_saved_keys.keyType, GROUP_USAGE,
5993                     bik->ik_keylen, (A_UINT8 *)&bik->ik_keyrsc,
5994                     bik->ik_keydata, key_op_ctrl, bik->ik_macaddr, NO_SYNC_WMIFLAG);
5995         }
5996     } else {
5997         status = wmi_add_krk_cmd(ar->arWmi, bik->ik_keydata);
5998     }
5999
6000 _reinstall_keys_out:
6001     ar->user_savedkeys_stat = USER_SAVEDKEYS_STAT_INIT;
6002     ar->user_key_ctrl      = 0;
6003
6004     return status;
6005 }
6006 #endif /* USER_KEYS */
6007
6008
6009 void
6010 ar6000_dset_open_req(
6011     void *context,
6012     A_UINT32 id,
6013     A_UINT32 targHandle,
6014     A_UINT32 targReplyFn,
6015     A_UINT32 targReplyArg)
6016 {
6017 }
6018
6019 void
6020 ar6000_dset_close(
6021     void *context,
6022     A_UINT32 access_cookie)
6023 {
6024     return;
6025 }
6026
6027 void
6028 ar6000_dset_data_req(
6029    void *context,
6030    A_UINT32 accessCookie,
6031    A_UINT32 offset,
6032    A_UINT32 length,
6033    A_UINT32 targBuf,
6034    A_UINT32 targReplyFn,
6035    A_UINT32 targReplyArg)
6036 {
6037 }
6038
6039 int
6040 ar6000_ap_mode_profile_commit(struct ar6_softc *ar)
6041 {
6042     WMI_CONNECT_CMD p;
6043     unsigned long  flags;
6044
6045     /* No change in AP's profile configuration */
6046     if(ar->ap_profile_flag==0) {
6047         A_PRINTF("COMMIT: No change in profile!!!\n");
6048         return -ENODATA;
6049     }
6050
6051     if(!ar->arSsidLen) {
6052         A_PRINTF("SSID not set!!!\n");
6053         return -ECHRNG;
6054     }
6055
6056     switch(ar->arAuthMode) {
6057     case NONE_AUTH:
6058         if((ar->arPairwiseCrypto != NONE_CRYPT) &&
6059 #ifdef WAPI_ENABLE
6060            (ar->arPairwiseCrypto != WAPI_CRYPT) &&
6061 #endif
6062            (ar->arPairwiseCrypto != WEP_CRYPT)) {
6063             A_PRINTF("Cipher not supported in AP mode Open auth\n");
6064             return -EOPNOTSUPP;
6065         }
6066         break;
6067     case WPA_PSK_AUTH:
6068     case WPA2_PSK_AUTH:
6069     case (WPA_PSK_AUTH|WPA2_PSK_AUTH):
6070         break;
6071     default:
6072         A_PRINTF("This key mgmt type not supported in AP mode\n");
6073         return -EOPNOTSUPP;
6074     }
6075
6076     /* Update the arNetworkType */
6077     ar->arNetworkType = ar->arNextMode;
6078
6079     A_MEMZERO(&p,sizeof(p));
6080     p.ssidLength = ar->arSsidLen;
6081     A_MEMCPY(p.ssid,ar->arSsid,p.ssidLength);
6082     p.channel = ar->arChannelHint;
6083     p.networkType = ar->arNetworkType;
6084
6085     p.dot11AuthMode = ar->arDot11AuthMode;
6086     p.authMode = ar->arAuthMode;
6087     p.pairwiseCryptoType = ar->arPairwiseCrypto;
6088     p.pairwiseCryptoLen = ar->arPairwiseCryptoLen;
6089     p.groupCryptoType = ar->arGroupCrypto;
6090     p.groupCryptoLen = ar->arGroupCryptoLen;
6091     p.ctrl_flags = ar->arConnectCtrlFlags;
6092
6093     ar->arConnected = FALSE;
6094
6095     wmi_ap_profile_commit(ar->arWmi, &p);
6096     spin_lock_irqsave(&ar->arLock, flags);
6097     ar->arConnected  = TRUE;
6098     netif_carrier_on(ar->arNetDev);
6099     spin_unlock_irqrestore(&ar->arLock, flags);
6100     ar->ap_profile_flag = 0;
6101     return 0;
6102 }
6103
6104 A_STATUS
6105 ar6000_connect_to_ap(struct ar6_softc *ar)
6106 {
6107     /* The ssid length check prevents second "essid off" from the user,
6108        to be treated as a connect cmd. The second "essid off" is ignored.
6109     */
6110     if((ar->arWmiReady == TRUE) && (ar->arSsidLen > 0) && ar->arNetworkType!=AP_NETWORK)
6111     {
6112         A_STATUS status;
6113         if((ADHOC_NETWORK != ar->arNetworkType) &&
6114            (NONE_AUTH==ar->arAuthMode)          &&
6115            (WEP_CRYPT==ar->arPairwiseCrypto)) {
6116                 ar6000_install_static_wep_keys(ar);
6117         }
6118
6119         if (!ar->arUserBssFilter) {
6120             if (wmi_bssfilter_cmd(ar->arWmi, ALL_BSS_FILTER, 0) != A_OK) {
6121                 return -EIO;
6122             }
6123         }
6124 #ifdef WAPI_ENABLE
6125         if (ar->arWapiEnable)  {
6126             ar->arPairwiseCrypto = WAPI_CRYPT;
6127             ar->arPairwiseCryptoLen = 0;
6128             ar->arGroupCrypto = WAPI_CRYPT;
6129             ar->arGroupCryptoLen = 0;
6130             ar->arAuthMode = NONE_AUTH;
6131             ar->arConnectCtrlFlags |= CONNECT_IGNORE_WPAx_GROUP_CIPHER;
6132         }
6133 #endif
6134         AR_DEBUG_PRINTF(ATH_DEBUG_WLAN_CONNECT,("Connect called with authmode %d dot11 auth %d"\
6135                         " PW crypto %d PW crypto Len %d GRP crypto %d"\
6136                         " GRP crypto Len %d\n",
6137                         ar->arAuthMode, ar->arDot11AuthMode,
6138                         ar->arPairwiseCrypto, ar->arPairwiseCryptoLen,
6139                         ar->arGroupCrypto, ar->arGroupCryptoLen));
6140         reconnect_flag = 0;
6141         /* Set the listen interval into 1000TUs or more. This value will be indicated to Ap in the conn.
6142            later set it back locally at the STA to 100/1000 TUs depending on the power mode */
6143         if ((ar->arNetworkType == INFRA_NETWORK)) {
6144             wmi_listeninterval_cmd(ar->arWmi, max(ar->arListenIntervalT, (A_UINT16)A_MAX_WOW_LISTEN_INTERVAL), 0);
6145         }
6146         status = wmi_connect_cmd(ar->arWmi, ar->arNetworkType,
6147                                  ar->arDot11AuthMode, ar->arAuthMode,
6148                                  ar->arPairwiseCrypto, ar->arPairwiseCryptoLen,
6149                                  ar->arGroupCrypto,ar->arGroupCryptoLen,
6150                                  ar->arSsidLen, ar->arSsid,
6151                                  ar->arReqBssid, ar->arChannelHint,
6152                                  ar->arConnectCtrlFlags);
6153         if (status != A_OK) {
6154             wmi_listeninterval_cmd(ar->arWmi, ar->arListenIntervalT, ar->arListenIntervalB);
6155             if (!ar->arUserBssFilter) {
6156                 wmi_bssfilter_cmd(ar->arWmi, NONE_BSS_FILTER, 0);
6157             }
6158             return status;
6159         }
6160
6161         if ((!(ar->arConnectCtrlFlags & CONNECT_DO_WPA_OFFLOAD)) &&
6162             ((WPA_PSK_AUTH == ar->arAuthMode) || (WPA2_PSK_AUTH == ar->arAuthMode)))
6163         {
6164             A_TIMEOUT_MS(&ar->disconnect_timer, A_DISCONNECT_TIMER_INTERVAL, 0);
6165         }
6166
6167         ar->arConnectCtrlFlags &= ~CONNECT_DO_WPA_OFFLOAD;
6168         
6169         ar->arConnectPending = TRUE;
6170         return status;    
6171     }
6172     return A_ERROR;
6173 }
6174
6175 A_STATUS
6176 ar6000_ap_mode_get_wpa_ie(struct ar6_softc *ar, struct ieee80211req_wpaie *wpaie)
6177 {
6178     sta_t *conn = NULL;
6179     conn = ieee80211_find_conn(ar, wpaie->wpa_macaddr);
6180
6181     A_MEMZERO(wpaie->wpa_ie, IEEE80211_MAX_IE);
6182     A_MEMZERO(wpaie->rsn_ie, IEEE80211_MAX_IE);
6183
6184     if(conn) {
6185         A_MEMCPY(wpaie->wpa_ie, conn->wpa_ie, IEEE80211_MAX_IE);
6186     }
6187
6188     return 0;
6189 }
6190
6191 A_STATUS
6192 is_iwioctl_allowed(A_UINT8 mode, A_UINT16 cmd)
6193 {
6194     if(cmd >= SIOCSIWCOMMIT && cmd <= SIOCGIWPOWER) {
6195         cmd -= SIOCSIWCOMMIT;
6196         if(sioctl_filter[cmd] == 0xFF) return A_OK;
6197         if(sioctl_filter[cmd] & mode) return A_OK;
6198     } else if(cmd >= SIOCIWFIRSTPRIV && cmd <= (SIOCIWFIRSTPRIV+30)) {
6199         cmd -= SIOCIWFIRSTPRIV;
6200         if(pioctl_filter[cmd] == 0xFF) return A_OK;
6201         if(pioctl_filter[cmd] & mode) return A_OK;
6202     } else {
6203         return A_ERROR;
6204     }
6205     return A_ENOTSUP;
6206 }
6207
6208 A_STATUS
6209 is_xioctl_allowed(A_UINT8 mode, int cmd)
6210 {
6211     if(sizeof(xioctl_filter)-1 < cmd) {
6212         A_PRINTF("Filter for this cmd=%d not defined\n",cmd);
6213         return 0;
6214     }
6215     if(xioctl_filter[cmd] == 0xFF) return A_OK;
6216     if(xioctl_filter[cmd] & mode) return A_OK;
6217     return A_ERROR;
6218 }
6219
6220 #ifdef WAPI_ENABLE
6221 int
6222 ap_set_wapi_key(struct ar6_softc *ar, void *ikey)
6223 {
6224     struct ieee80211req_key *ik = (struct ieee80211req_key *)ikey;
6225     KEY_USAGE   keyUsage = 0;
6226     A_STATUS    status;
6227
6228     if (A_MEMCMP(ik->ik_macaddr, bcast_mac, IEEE80211_ADDR_LEN) == 0) {
6229         keyUsage = GROUP_USAGE;
6230     } else {
6231         keyUsage = PAIRWISE_USAGE;
6232     }
6233     A_PRINTF("WAPI_KEY: Type:%d ix:%d mac:%02x:%02x len:%d\n",
6234         keyUsage, ik->ik_keyix, ik->ik_macaddr[4], ik->ik_macaddr[5],
6235         ik->ik_keylen);
6236
6237     status = wmi_addKey_cmd(ar->arWmi, ik->ik_keyix, WAPI_CRYPT, keyUsage,
6238                             ik->ik_keylen, (A_UINT8 *)&ik->ik_keyrsc,
6239                             ik->ik_keydata, KEY_OP_INIT_VAL, ik->ik_macaddr,
6240                             SYNC_BOTH_WMIFLAG);
6241
6242     if (A_OK != status) {
6243         return -EIO;
6244     }
6245     return 0;
6246 }
6247 #endif
6248
6249 void ar6000_peer_event(
6250     void *context,
6251     A_UINT8 eventCode,
6252     A_UINT8 *macAddr)
6253 {
6254     A_UINT8 pos;
6255
6256     for (pos=0;pos<6;pos++)
6257         printk("%02x: ",*(macAddr+pos));
6258     printk("\n");
6259 }
6260
6261 #ifdef HTC_TEST_SEND_PKTS
6262 #define HTC_TEST_DUPLICATE 8
6263 static void DoHTCSendPktsTest(AR_SOFTC_T *ar, int MapNo, HTC_ENDPOINT_ID eid, struct sk_buff *dupskb)
6264 {
6265     struct ar_cookie *cookie;
6266     struct ar_cookie *cookieArray[HTC_TEST_DUPLICATE];
6267     struct sk_buff   *new_skb;
6268     int    i;
6269     int    pkts = 0;
6270     HTC_PACKET_QUEUE pktQueue;
6271     EPPING_HEADER    *eppingHdr;
6272
6273     eppingHdr = A_NETBUF_DATA(dupskb);
6274
6275     if (eppingHdr->Cmd_h == EPPING_CMD_NO_ECHO) {
6276         /* skip test if this is already a tx perf test */
6277         return;
6278     }
6279
6280     for (i = 0; i < HTC_TEST_DUPLICATE; i++,pkts++) {
6281         AR6000_SPIN_LOCK(&ar->arLock, 0);
6282         cookie = ar6000_alloc_cookie(ar);
6283         if (cookie != NULL) {
6284             ar->arTxPending[eid]++;
6285             ar->arTotalTxDataPending++;
6286         }
6287
6288         AR6000_SPIN_UNLOCK(&ar->arLock, 0);
6289
6290         if (NULL == cookie) {
6291             break;
6292         }
6293
6294         new_skb = A_NETBUF_ALLOC(A_NETBUF_LEN(dupskb));
6295
6296         if (new_skb == NULL) {
6297             AR6000_SPIN_LOCK(&ar->arLock, 0);
6298             ar6000_free_cookie(ar,cookie);
6299             AR6000_SPIN_UNLOCK(&ar->arLock, 0);
6300             break;
6301         }
6302
6303         A_NETBUF_PUT_DATA(new_skb, A_NETBUF_DATA(dupskb), A_NETBUF_LEN(dupskb));
6304         cookie->arc_bp[0] = (unsigned long)new_skb;
6305         cookie->arc_bp[1] = MapNo;
6306         SET_HTC_PACKET_INFO_TX(&cookie->HtcPkt,
6307                                cookie,
6308                                A_NETBUF_DATA(new_skb),
6309                                A_NETBUF_LEN(new_skb),
6310                                eid,
6311                                AR6K_DATA_PKT_TAG);
6312
6313         cookieArray[i] = cookie;
6314
6315         {
6316             EPPING_HEADER *pHdr = (EPPING_HEADER *)A_NETBUF_DATA(new_skb);
6317             pHdr->Cmd_h = EPPING_CMD_NO_ECHO;  /* do not echo the packet */
6318         }
6319     }
6320
6321     if (pkts == 0) {
6322         return;
6323     }
6324
6325     INIT_HTC_PACKET_QUEUE(&pktQueue);
6326
6327     for (i = 0; i < pkts; i++) {
6328         HTC_PACKET_ENQUEUE(&pktQueue,&cookieArray[i]->HtcPkt);
6329     }
6330
6331     HTCSendPktsMultiple(ar->arHtcTarget, &pktQueue);
6332
6333 }
6334 #endif
6335
6336 #ifdef CONFIG_AP_VIRTUAL_ADAPTER_SUPPORT
6337 /*
6338  * Add support for adding and removing a virtual adapter for soft AP.
6339  * Some OS requires different adapters names for station and soft AP mode.
6340  * To support these requirement, create and destory a netdevice  instance
6341  * when the AP mode is operational. A full fledged support for virual device
6342  * is not implemented. Rather a virtual interface is created and is linked
6343  * with the existing physical device instance during the operation of the 
6344  * AP mode.
6345  */
6346
6347 A_STATUS ar6000_start_ap_interface(AR_SOFTC_T *ar)
6348 {
6349     AR_VIRTUAL_INTERFACE_T *arApDev;
6350
6351     /* Change net_device to point to AP instance */
6352     arApDev = (AR_VIRTUAL_INTERFACE_T *)ar->arApDev;
6353     ar->arNetDev = arApDev->arNetDev;
6354
6355     return A_OK;
6356 }
6357
6358 A_STATUS ar6000_stop_ap_interface(AR_SOFTC_T *ar)
6359 {
6360     AR_VIRTUAL_INTERFACE_T *arApDev;
6361
6362     /* Change net_device to point to sta instance */
6363     arApDev = (AR_VIRTUAL_INTERFACE_T *)ar->arApDev;
6364     if (arApDev) {
6365         ar->arNetDev = arApDev->arStaNetDev;
6366     }
6367
6368     return A_OK;
6369 }
6370
6371
6372 A_STATUS ar6000_create_ap_interface(AR_SOFTC_T *ar, char *ap_ifname) 
6373 {
6374     struct net_device *dev;
6375     AR_VIRTUAL_INTERFACE_T *arApDev;
6376
6377     dev = alloc_etherdev(sizeof(AR_VIRTUAL_INTERFACE_T));
6378     if (dev == NULL) {
6379         AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("ar6000_create_ap_interface: can't alloc etherdev\n"));
6380         return A_ERROR;
6381     } 
6382     
6383     ether_setup(dev);
6384     init_netdev(dev, ap_ifname);
6385
6386     if (register_netdev(dev)) {
6387         AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("ar6000_create_ap_interface: register_netdev failed\n"));
6388         return A_ERROR;
6389     }
6390
6391     arApDev = netdev_priv(dev);
6392     arApDev->arDev = ar;
6393     arApDev->arNetDev = dev;
6394     arApDev->arStaNetDev = ar->arNetDev;
6395
6396     ar->arApDev = arApDev;
6397     arApNetDev = dev;
6398
6399     /* Copy the MAC address */
6400     A_MEMCPY(dev->dev_addr, ar->arNetDev->dev_addr, AR6000_ETH_ADDR_LEN);
6401
6402     return A_OK;
6403 }
6404
6405 A_STATUS ar6000_add_ap_interface(AR_SOFTC_T *ar, char *ap_ifname) 
6406 {
6407     /* Interface already added, need not proceed further */
6408     if (ar->arApDev != NULL) {
6409         AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("ar6000_add_ap_interface: interface already present \n"));
6410         return A_OK;
6411     }
6412
6413     if (ar6000_create_ap_interface(ar, ap_ifname) != A_OK) {
6414         return A_ERROR;
6415     }
6416
6417     A_PRINTF("Add AP interface %s \n",ap_ifname);
6418
6419     return ar6000_start_ap_interface(ar);
6420 }
6421
6422 A_STATUS ar6000_remove_ap_interface(AR_SOFTC_T *ar)
6423 {
6424     if (arApNetDev) {
6425         ar6000_stop_ap_interface(ar);
6426
6427         unregister_netdev(arApNetDev);
6428         free_netdev(apApNetDev);
6429
6430         A_PRINTF("Remove AP interface\n");
6431     }
6432     ar->arApDev = NULL;
6433     arApNetDev = NULL;
6434
6435     
6436     return A_OK;
6437 }
6438 #endif /* CONFIG_AP_VIRTUAL_ADAPTER_SUPPORT */
6439
6440
6441 #ifdef EXPORT_HCI_BRIDGE_INTERFACE
6442 EXPORT_SYMBOL(setupbtdev);
6443 #endif