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