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