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