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