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