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