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