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