Merge branch 'for-2.6.34-incoming' into for-2.6.35-incoming
[pandora-kernel.git] / drivers / staging / rtl8192su / r8192U_core.c
1 /******************************************************************************
2  * Copyright(c) 2008 - 2010 Realtek Corporation. All rights reserved.
3  * Linux device driver for RTL8192U
4  *
5  * Based on the r8187 driver, which is:
6  * Copyright 2004-2005 Andrea Merello <andreamrl@tiscali.it>, et al.
7  * This program is free software; you can redistribute it and/or modify it
8  * under the terms of version 2 of the GNU General Public License as
9  * published by the Free Software Foundation.
10  *
11  * This program is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
14  * more details.
15  *
16  * You should have received a copy of the GNU General Public License along with
17  * this program; if not, write to the Free Software Foundation, Inc.,
18  * 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
19  *
20  * The full GNU General Public License is included in this distribution in the
21  * file called LICENSE.
22  *
23  * Contact Information:
24  * Jerry chuang <wlanfae@realtek.com>
25  */
26
27 #include <linux/vmalloc.h>
28 #include <linux/slab.h>
29
30 #undef LOOP_TEST
31 #undef DUMP_RX
32 #undef DUMP_TX
33 #undef DEBUG_TX_DESC2
34 #undef RX_DONT_PASS_UL
35 #undef DEBUG_EPROM
36 #undef DEBUG_RX_VERBOSE
37 #undef DUMMY_RX
38 #undef DEBUG_ZERO_RX
39 #undef DEBUG_RX_SKB
40 #undef DEBUG_TX_FRAG
41 #undef DEBUG_RX_FRAG
42 #undef DEBUG_TX_FILLDESC
43 #undef DEBUG_TX
44 #undef DEBUG_IRQ
45 #undef DEBUG_RX
46 #undef DEBUG_RXALLOC
47 #undef DEBUG_REGISTERS
48 #undef DEBUG_RING
49 #undef DEBUG_IRQ_TASKLET
50 #undef DEBUG_TX_ALLOC
51 #undef DEBUG_TX_DESC
52
53 #define CONFIG_RTL8192_IO_MAP
54
55 #include <asm/uaccess.h>
56 #include "r8192U.h"
57 #include "r8180_93cx6.h"   /* Card EEPROM */
58 #include "r8192U_wx.h"
59
60 #include "r8192S_rtl8225.h"
61 #include "r8192S_hw.h"
62 #include "r8192S_phy.h"
63 #include "r8192S_phyreg.h"
64 #include "r8192S_Efuse.h"
65
66 #include "r819xU_cmdpkt.h"
67 #include "r8192U_dm.h"
68 //#include "r8192xU_phyreg.h"
69 #include <linux/usb.h>
70
71 #include "r8192U_pm.h"
72
73 #include "ieee80211/dot11d.h"
74
75
76
77 u32 rt_global_debug_component = \
78 //                              COMP_TRACE      |
79 //                              COMP_DBG        |
80 //                              COMP_INIT       |
81 //                              COMP_RECV       |
82 //                              COMP_SEND       |
83 //                              COMP_IO         |
84                                 COMP_POWER      |
85 //                              COMP_EPROM      |
86                                 COMP_SWBW       |
87                                 COMP_POWER_TRACKING |
88                                 COMP_TURBO      |
89                                 COMP_QOS        |
90 //                              COMP_RATE       |
91 //                              COMP_RM         |
92                                 COMP_DIG        |
93 //                              COMP_EFUSE      |
94 //                              COMP_CH         |
95 //                              COMP_TXAGC      |
96                                 COMP_HIPWR      |
97 //                              COMP_HALDM      |
98                                 COMP_SEC        |
99                                 COMP_LED        |
100 //                              COMP_RF         |
101 //                              COMP_RXDESC     |
102                                 COMP_FIRMWARE   |
103                                 COMP_HT         |
104                                 COMP_AMSDU      |
105                                 COMP_SCAN       |
106 //                              COMP_CMD        |
107                                 COMP_DOWN       |
108                                 COMP_RESET      |
109                                 COMP_ERR; //always open err flags on
110
111 #define TOTAL_CAM_ENTRY 32
112 #define CAM_CONTENT_COUNT 8
113
114 static const struct usb_device_id rtl8192_usb_id_tbl[] = {
115         /* Realtek */
116         {USB_DEVICE(0x0bda, 0x8171)},
117         {USB_DEVICE(0x0bda, 0x8192)},
118         {USB_DEVICE(0x0bda, 0x8709)},
119         /* Corega */
120         {USB_DEVICE(0x07aa, 0x0043)},
121         /* Belkin */
122         {USB_DEVICE(0x050d, 0x805E)},
123         {USB_DEVICE(0x050d, 0x815F)}, /* Belkin F5D8053 v6 */
124         /* Sitecom */
125         {USB_DEVICE(0x0df6, 0x0031)},
126         {USB_DEVICE(0x0df6, 0x004b)},   /* WL-349 */
127         /* EnGenius */
128         {USB_DEVICE(0x1740, 0x9201)},
129         /* Dlink */
130         {USB_DEVICE(0x2001, 0x3301)},
131         /* Zinwell */
132         {USB_DEVICE(0x5a57, 0x0290)},
133         /* Guillemot */
134         {USB_DEVICE(0x06f8, 0xe031)},
135         //92SU
136         {USB_DEVICE(0x0bda, 0x8172)},
137         {}
138 };
139
140 MODULE_LICENSE("GPL");
141 MODULE_VERSION("V 1.1");
142 MODULE_DEVICE_TABLE(usb, rtl8192_usb_id_tbl);
143 MODULE_DESCRIPTION("Linux driver for Realtek RTL8192 USB WiFi cards");
144
145 static char* ifname = "wlan%d";
146 static int hwwep = 1;  //default use hw. set 0 to use software security
147 static int channels = 0x3fff;
148
149
150
151 module_param(ifname, charp, S_IRUGO|S_IWUSR );
152 //module_param(hwseqnum,int, S_IRUGO|S_IWUSR);
153 module_param(hwwep,int, S_IRUGO|S_IWUSR);
154 module_param(channels,int, S_IRUGO|S_IWUSR);
155
156 MODULE_PARM_DESC(ifname," Net interface name, wlan%d=default");
157 //MODULE_PARM_DESC(hwseqnum," Try to use hardware 802.11 header sequence numbers. Zero=default");
158 MODULE_PARM_DESC(hwwep," Try to use hardware security support. ");
159 MODULE_PARM_DESC(channels," Channel bitmask for specific locales. NYI");
160
161 static int __devinit rtl8192_usb_probe(struct usb_interface *intf,
162                          const struct usb_device_id *id);
163 static void __devexit rtl8192_usb_disconnect(struct usb_interface *intf);
164
165 static struct usb_driver rtl8192_usb_driver = {
166         .name           = RTL819xU_MODULE_NAME,           /* Driver name   */
167         .id_table       = rtl8192_usb_id_tbl,             /* PCI_ID table  */
168         .probe          = rtl8192_usb_probe,              /* probe fn      */
169         .disconnect     = rtl8192_usb_disconnect,         /* remove fn     */
170         .suspend        = rtl8192U_suspend,               /* PM suspend fn */
171         .resume         = rtl8192U_resume,                 /* PM resume fn  */
172         .reset_resume   = rtl8192U_resume,                 /* PM reset resume fn  */
173 };
174
175
176 static void     rtl8192SU_read_eeprom_info(struct net_device *dev);
177 short   rtl8192SU_tx(struct net_device *dev, struct sk_buff* skb);
178 void    rtl8192SU_rx_nomal(struct sk_buff* skb);
179 void    rtl8192SU_rx_cmd(struct sk_buff *skb);
180 bool    rtl8192SU_adapter_start(struct net_device *dev);
181 short   rtl8192SU_tx_cmd(struct net_device *dev, struct sk_buff *skb);
182 void    rtl8192SU_link_change(struct net_device *dev);
183 void    InitialGain8192S(struct net_device *dev,u8 Operation);
184 void    rtl8192SU_query_rxdesc_status(struct sk_buff *skb, struct ieee80211_rx_stats *stats, bool bIsRxAggrSubframe);
185
186 struct rtl819x_ops rtl8192su_ops = {
187         .nic_type = NIC_8192SU,
188         .rtl819x_read_eeprom_info = rtl8192SU_read_eeprom_info,
189         .rtl819x_tx = rtl8192SU_tx,
190         .rtl819x_tx_cmd = rtl8192SU_tx_cmd,
191         .rtl819x_rx_nomal = rtl8192SU_rx_nomal,
192         .rtl819x_rx_cmd = rtl8192SU_rx_cmd,
193         .rtl819x_adapter_start = rtl8192SU_adapter_start,
194         .rtl819x_link_change = rtl8192SU_link_change,
195         .rtl819x_initial_gain = InitialGain8192S,
196         .rtl819x_query_rxdesc_status = rtl8192SU_query_rxdesc_status,
197 };
198
199
200 typedef struct _CHANNEL_LIST
201 {
202         u8      Channel[32];
203         u8      Len;
204 }CHANNEL_LIST, *PCHANNEL_LIST;
205
206 static CHANNEL_LIST ChannelPlan[] = {
207         {{1,2,3,4,5,6,7,8,9,10,11,36,40,44,48,52,56,60,64,149,153,157,161,165},24},             //FCC
208         {{1,2,3,4,5,6,7,8,9,10,11},11},                                                 //IC
209         {{1,2,3,4,5,6,7,8,9,10,11,12,13,36,40,44,48,52,56,60,64},21},   //ETSI
210         {{1,2,3,4,5,6,7,8,9,10,11,12,13},13},    //Spain. Change to ETSI.
211         {{1,2,3,4,5,6,7,8,9,10,11,12,13},13},   //France. Change to ETSI.
212         {{1,2,3,4,5,6,7,8,9,10,11,12,13,14,36,40,44,48,52,56,60,64},22},        //MKK                                   //MKK
213         {{1,2,3,4,5,6,7,8,9,10,11,12,13,14,36,40,44,48,52,56,60,64},22},//MKK1
214         {{1,2,3,4,5,6,7,8,9,10,11,12,13},13},   //Israel.
215         {{1,2,3,4,5,6,7,8,9,10,11,12,13,14,36,40,44,48,52,56,60,64},22},                        // For 11a , TELEC
216         {{1,2,3,4,5,6,7,8,9,10,11,12,13,14,36,40,44,48,52,56,60,64}, 22},    //MIC
217         {{1,2,3,4,5,6,7,8,9,10,11,12,13,14},14}                                 //For Global Domain. 1-11:active scan, 12-14 passive scan. //+YJ, 080626
218 };
219
220 static void rtl819x_set_channel_map(u8 channel_plan, struct r8192_priv* priv)
221 {
222         int i, max_chan=-1, min_chan=-1;
223         struct ieee80211_device* ieee = priv->ieee80211;
224         switch (channel_plan)
225         {
226                 case COUNTRY_CODE_FCC:
227                 case COUNTRY_CODE_IC:
228                 case COUNTRY_CODE_ETSI:
229                 case COUNTRY_CODE_SPAIN:
230                 case COUNTRY_CODE_FRANCE:
231                 case COUNTRY_CODE_MKK:
232                 case COUNTRY_CODE_MKK1:
233                 case COUNTRY_CODE_ISRAEL:
234                 case COUNTRY_CODE_TELEC:
235                 case COUNTRY_CODE_MIC:
236                 {
237                         Dot11d_Init(ieee);
238                         ieee->bGlobalDomain = false;
239                         //acturally 8225 & 8256 rf chip only support B,G,24N mode
240                         if ((priv->rf_chip == RF_8225) || (priv->rf_chip == RF_8256) || (priv->rf_chip == RF_6052))
241                         {
242                                 min_chan = 1;
243                                 max_chan = 14;
244                         }
245                         else
246                         {
247                                 RT_TRACE(COMP_ERR, "unknown rf chip, can't set channel map in function:%s()\n", __FUNCTION__);
248                         }
249                         if (ChannelPlan[channel_plan].Len != 0){
250                                 // Clear old channel map
251                                 memset(GET_DOT11D_INFO(ieee)->channel_map, 0, sizeof(GET_DOT11D_INFO(ieee)->channel_map));
252                                 // Set new channel map
253                                 for (i=0;i<ChannelPlan[channel_plan].Len;i++)
254                                 {
255                                         if (ChannelPlan[channel_plan].Channel[i] < min_chan || ChannelPlan[channel_plan].Channel[i] > max_chan)
256                                         break;
257                                         GET_DOT11D_INFO(ieee)->channel_map[ChannelPlan[channel_plan].Channel[i]] = 1;
258                                 }
259                         }
260                         break;
261                 }
262                 case COUNTRY_CODE_GLOBAL_DOMAIN:
263                 {
264                         GET_DOT11D_INFO(ieee)->bEnabled = 0;//this flag enabled to follow 11d country IE setting, otherwise, it shall follow global domain settings.
265                         Dot11d_Reset(ieee);
266                         ieee->bGlobalDomain = true;
267                         break;
268                 }
269                 default:
270                         break;
271         }
272         return;
273 }
274
275 #define eqMacAddr(a,b) ( ((a)[0]==(b)[0] && (a)[1]==(b)[1] && (a)[2]==(b)[2] && (a)[3]==(b)[3] && (a)[4]==(b)[4] && (a)[5]==(b)[5]) ? 1:0 )
276
277 #define         rx_hal_is_cck_rate(_pDesc)\
278                         ((_pDesc->RxMCS  == DESC92S_RATE1M ||\
279                         _pDesc->RxMCS == DESC92S_RATE2M ||\
280                         _pDesc->RxMCS == DESC92S_RATE5_5M ||\
281                         _pDesc->RxMCS == DESC92S_RATE11M) &&\
282                         !_pDesc->RxHT)
283
284 #define         tx_hal_is_cck_rate(_DataRate)\
285                         ( _DataRate == MGN_1M ||\
286                          _DataRate == MGN_2M ||\
287                          _DataRate == MGN_5_5M ||\
288                          _DataRate == MGN_11M )
289
290
291
292
293 void CamResetAllEntry(struct net_device *dev)
294 {
295 #if 1
296         u32 ulcommand = 0;
297         //2004/02/11  In static WEP, OID_ADD_KEY or OID_ADD_WEP are set before STA associate to AP.
298         // However, ResetKey is called on OID_802_11_INFRASTRUCTURE_MODE and MlmeAssociateRequest
299         // In this condition, Cam can not be reset because upper layer will not set this static key again.
300         //if(Adapter->EncAlgorithm == WEP_Encryption)
301         //      return;
302 //debug
303         //DbgPrint("========================================\n");
304         //DbgPrint("                            Call ResetAllEntry                                              \n");
305         //DbgPrint("========================================\n\n");
306         ulcommand |= BIT31|BIT30;
307         write_nic_dword(dev, RWCAM, ulcommand);
308 #else
309         for(ucIndex=0;ucIndex<TOTAL_CAM_ENTRY;ucIndex++)
310                 CAM_mark_invalid(dev, ucIndex);
311         for(ucIndex=0;ucIndex<TOTAL_CAM_ENTRY;ucIndex++)
312                 CAM_empty_entry(dev, ucIndex);
313 #endif
314
315 }
316
317
318 void write_cam(struct net_device *dev, u8 addr, u32 data)
319 {
320         write_nic_dword(dev, WCAMI, data);
321         write_nic_dword(dev, RWCAM, BIT31|BIT16|(addr&0xff) );
322 }
323
324 u32 read_cam(struct net_device *dev, u8 addr)
325 {
326         write_nic_dword(dev, RWCAM, 0x80000000|(addr&0xff) );
327         return read_nic_dword(dev, 0xa8);
328 }
329
330 void write_nic_byte_E(struct net_device *dev, int indx, u8 data)
331 {
332         int status;
333         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
334         struct usb_device *udev = priv->udev;
335
336         status = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
337                                RTL8187_REQ_SET_REGS, RTL8187_REQT_WRITE,
338                                indx|0xfe00, 0, &data, 1, HZ / 2);
339
340         if (status < 0)
341         {
342                 printk("write_nic_byte_E TimeOut! status:%d\n", status);
343         }
344 }
345
346 u8 read_nic_byte_E(struct net_device *dev, int indx)
347 {
348         int status;
349         u8 data;
350         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
351         struct usb_device *udev = priv->udev;
352
353         status = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0),
354                                RTL8187_REQ_GET_REGS, RTL8187_REQT_READ,
355                                indx|0xfe00, 0, &data, 1, HZ / 2);
356
357         if (status < 0)
358         {
359                 printk("read_nic_byte_E TimeOut! status:%d\n", status);
360         }
361
362         return data;
363 }
364 //as 92U has extend page from 4 to 16, so modify functions below.
365 void write_nic_byte(struct net_device *dev, int indx, u8 data)
366 {
367         int status;
368
369         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
370         struct usb_device *udev = priv->udev;
371
372         status = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
373                                RTL8187_REQ_SET_REGS, RTL8187_REQT_WRITE,
374                                indx, 0, &data, 1, HZ / 2);
375
376         if (status < 0)
377         {
378                 printk("write_nic_byte TimeOut! status:%d\n", status);
379         }
380
381
382 }
383
384
385 void write_nic_word(struct net_device *dev, int indx, u16 data)
386 {
387
388         int status;
389
390         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
391         struct usb_device *udev = priv->udev;
392
393         status = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
394                                RTL8187_REQ_SET_REGS, RTL8187_REQT_WRITE,
395                                indx, 0, &data, 2, HZ / 2);
396
397         if (status < 0)
398         {
399                 printk("write_nic_word TimeOut! status:%d\n", status);
400         }
401
402 }
403
404
405 void write_nic_dword(struct net_device *dev, int indx, u32 data)
406 {
407
408         int status;
409
410         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
411         struct usb_device *udev = priv->udev;
412
413         status = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
414                                RTL8187_REQ_SET_REGS, RTL8187_REQT_WRITE,
415                                indx, 0, &data, 4, HZ / 2);
416
417
418         if (status < 0)
419         {
420                 printk("write_nic_dword TimeOut! status:%d\n", status);
421         }
422
423 }
424
425
426
427 u8 read_nic_byte(struct net_device *dev, int indx)
428 {
429         u8 data;
430         int status;
431         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
432         struct usb_device *udev = priv->udev;
433
434         status = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0),
435                                RTL8187_REQ_GET_REGS, RTL8187_REQT_READ,
436                                indx, 0, &data, 1, HZ / 2);
437
438         if (status < 0)
439         {
440                 printk("read_nic_byte TimeOut! status:%d\n", status);
441         }
442
443         return data;
444 }
445
446
447
448 u16 read_nic_word(struct net_device *dev, int indx)
449 {
450         u16 data;
451         int status;
452         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
453         struct usb_device *udev = priv->udev;
454
455         status = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0),
456                                RTL8187_REQ_GET_REGS, RTL8187_REQT_READ,
457                                indx, 0, &data, 2, HZ / 2);
458
459         if (status < 0)
460         {
461                 printk("read_nic_word TimeOut! status:%d\n", status);
462         }
463
464
465         return data;
466 }
467
468 u16 read_nic_word_E(struct net_device *dev, int indx)
469 {
470         u16 data;
471         int status;
472         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
473         struct usb_device *udev = priv->udev;
474
475         status = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0),
476                                RTL8187_REQ_GET_REGS, RTL8187_REQT_READ,
477                                indx|0xfe00, 0, &data, 2, HZ / 2);
478
479         if (status < 0)
480         {
481                 printk("read_nic_word TimeOut! status:%d\n", status);
482         }
483
484
485         return data;
486 }
487
488 u32 read_nic_dword(struct net_device *dev, int indx)
489 {
490         u32 data;
491         int status;
492 //      int result;
493
494         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
495         struct usb_device *udev = priv->udev;
496
497         status = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0),
498                                RTL8187_REQ_GET_REGS, RTL8187_REQT_READ,
499                                indx, 0, &data, 4, HZ / 2);
500 //      if(0 != result) {
501 //        printk(KERN_WARNING "read size of data = %d\, date = %d\n", result, data);
502 //      }
503
504         if (status < 0)
505         {
506                 printk("read_nic_dword TimeOut! status:%d\n", status);
507                 if(status == -ENODEV) {
508                         priv->usb_error = true;
509                 }
510         }
511
512
513
514         return data;
515 }
516
517
518 //u8 read_phy_cck(struct net_device *dev, u8 adr);
519 //u8 read_phy_ofdm(struct net_device *dev, u8 adr);
520 /* this might still called in what was the PHY rtl8185/rtl8192 common code
521  * plans are to possibilty turn it again in one common code...
522  */
523 inline void force_pci_posting(struct net_device *dev)
524 {
525 }
526
527
528 static struct net_device_stats *rtl8192_stats(struct net_device *dev);
529 void rtl8192_commit(struct net_device *dev);
530 //void rtl8192_restart(struct net_device *dev);
531 void rtl8192_restart(struct work_struct *work);
532 //void rtl8192_rq_tx_ack(struct work_struct *work);
533
534 void watch_dog_timer_callback(unsigned long data);
535
536 /****************************************************************************
537    -----------------------------PROCFS STUFF-------------------------
538 *****************************************************************************/
539
540 static struct proc_dir_entry *rtl8192_proc = NULL;
541
542
543
544 static int proc_get_stats_ap(char *page, char **start,
545                           off_t offset, int count,
546                           int *eof, void *data)
547 {
548         struct net_device *dev = data;
549         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
550         struct ieee80211_device *ieee = priv->ieee80211;
551         struct ieee80211_network *target;
552
553         int len = 0;
554
555         list_for_each_entry(target, &ieee->network_list, list) {
556
557                 len += snprintf(page + len, count - len,
558                 "%s ", target->ssid);
559
560                 if(target->wpa_ie_len>0 || target->rsn_ie_len>0){
561                         len += snprintf(page + len, count - len,
562                         "WPA\n");
563                 }
564                 else{
565                         len += snprintf(page + len, count - len,
566                         "non_WPA\n");
567                 }
568
569         }
570
571         *eof = 1;
572         return len;
573 }
574
575 static int proc_get_registers(char *page, char **start,
576                           off_t offset, int count,
577                           int *eof, void *data)
578 {
579         struct net_device *dev = data;
580 //      struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
581
582         int len = 0;
583         int i,n,page0,page1,page2;
584
585         int max=0xff;
586         page0 = 0x000;
587         page1 = 0x100;
588         page2 = 0x800;
589
590         /* This dump the current register page */
591         if(!IS_BB_REG_OFFSET_92S(page0)){
592                 len += snprintf(page + len, count - len,
593                                 "\n####################page %x##################\n ", (page0>>8));
594                 for(n=0;n<=max;)
595                 {
596                         len += snprintf(page + len, count - len,
597                                         "\nD:  %2x > ",n);
598                         for(i=0;i<16 && n<=max;i++,n++)
599                                 len += snprintf(page + len, count - len,
600                                                 "%2.2x ",read_nic_byte(dev,(page0|n)));
601                 }
602         }else{
603                 len += snprintf(page + len, count - len,
604                                 "\n####################page %x##################\n ", (page0>>8));
605                 for(n=0;n<=max;)
606                 {
607                         len += snprintf(page + len, count - len, "\nD:  %2x > ",n);
608                         for(i=0;i<4 && n<=max;n+=4,i++)
609                                 len += snprintf(page + len, count - len,
610                                                 "%8.8x ",rtl8192_QueryBBReg(dev,(page0|n), bMaskDWord));
611                 }
612         }
613         len += snprintf(page + len, count - len,"\n");
614         *eof = 1;
615         return len;
616
617 }
618 static int proc_get_registers_1(char *page, char **start,
619                           off_t offset, int count,
620                           int *eof, void *data)
621 {
622         struct net_device *dev = data;
623 //      struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
624
625         int len = 0;
626         int i,n,page0;
627
628         int max=0xff;
629         page0 = 0x100;
630
631         /* This dump the current register page */
632                 len += snprintf(page + len, count - len,
633                                 "\n####################page %x##################\n ", (page0>>8));
634                 for(n=0;n<=max;)
635                 {
636                         len += snprintf(page + len, count - len,
637                                         "\nD:  %2x > ",n);
638                         for(i=0;i<16 && n<=max;i++,n++)
639                                 len += snprintf(page + len, count - len,
640                                                 "%2.2x ",read_nic_byte(dev,(page0|n)));
641                 }
642         len += snprintf(page + len, count - len,"\n");
643         *eof = 1;
644         return len;
645
646 }
647 static int proc_get_registers_2(char *page, char **start,
648                           off_t offset, int count,
649                           int *eof, void *data)
650 {
651         struct net_device *dev = data;
652 //      struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
653
654         int len = 0;
655         int i,n,page0;
656
657         int max=0xff;
658         page0 = 0x200;
659
660         /* This dump the current register page */
661                 len += snprintf(page + len, count - len,
662                                 "\n####################page %x##################\n ", (page0>>8));
663                 for(n=0;n<=max;)
664                 {
665                         len += snprintf(page + len, count - len,
666                                         "\nD:  %2x > ",n);
667                         for(i=0;i<16 && n<=max;i++,n++)
668                                 len += snprintf(page + len, count - len,
669                                                 "%2.2x ",read_nic_byte(dev,(page0|n)));
670                 }
671         len += snprintf(page + len, count - len,"\n");
672         *eof = 1;
673         return len;
674
675 }
676 static int proc_get_registers_8(char *page, char **start,
677                           off_t offset, int count,
678                           int *eof, void *data)
679 {
680         struct net_device *dev = data;
681
682         int len = 0;
683         int i,n,page0;
684
685         int max=0xff;
686         page0 = 0x800;
687
688         /* This dump the current register page */
689                 len += snprintf(page + len, count - len,
690                                 "\n####################page %x##################\n ", (page0>>8));
691                 for(n=0;n<=max;)
692                 {
693                         len += snprintf(page + len, count - len, "\nD:  %2x > ",n);
694                         for(i=0;i<4 && n<=max;n+=4,i++)
695                                 len += snprintf(page + len, count - len,
696                                                 "%8.8x ",rtl8192_QueryBBReg(dev,(page0|n), bMaskDWord));
697                 }
698         len += snprintf(page + len, count - len,"\n");
699         *eof = 1;
700         return len;
701
702         }
703 static int proc_get_registers_9(char *page, char **start,
704                           off_t offset, int count,
705                           int *eof, void *data)
706 {
707         struct net_device *dev = data;
708 //      struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
709
710         int len = 0;
711         int i,n,page0;
712
713         int max=0xff;
714         page0 = 0x900;
715
716         /* This dump the current register page */
717                 len += snprintf(page + len, count - len,
718                                 "\n####################page %x##################\n ", (page0>>8));
719                 for(n=0;n<=max;)
720                 {
721                         len += snprintf(page + len, count - len, "\nD:  %2x > ",n);
722                         for(i=0;i<4 && n<=max;n+=4,i++)
723                         len += snprintf(page + len, count - len,
724                                                 "%8.8x ",rtl8192_QueryBBReg(dev,(page0|n), bMaskDWord));
725                 }
726         len += snprintf(page + len, count - len,"\n");
727         *eof = 1;
728         return len;
729 }
730 static int proc_get_registers_a(char *page, char **start,
731                           off_t offset, int count,
732                           int *eof, void *data)
733 {
734         struct net_device *dev = data;
735 //      struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
736
737         int len = 0;
738         int i,n,page0;
739
740         int max=0xff;
741         page0 = 0xa00;
742
743         /* This dump the current register page */
744                                 len += snprintf(page + len, count - len,
745                                 "\n####################page %x##################\n ", (page0>>8));
746                 for(n=0;n<=max;)
747                 {
748                         len += snprintf(page + len, count - len, "\nD:  %2x > ",n);
749                         for(i=0;i<4 && n<=max;n+=4,i++)
750                                 len += snprintf(page + len, count - len,
751                                                 "%8.8x ",rtl8192_QueryBBReg(dev,(page0|n), bMaskDWord));
752                 }
753         len += snprintf(page + len, count - len,"\n");
754         *eof = 1;
755         return len;
756 }
757 static int proc_get_registers_b(char *page, char **start,
758                           off_t offset, int count,
759                           int *eof, void *data)
760 {
761         struct net_device *dev = data;
762 //      struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
763
764         int len = 0;
765         int i,n,page0;
766
767         int max=0xff;
768         page0 = 0xb00;
769
770         /* This dump the current register page */
771                 len += snprintf(page + len, count - len,
772                                 "\n####################page %x##################\n ", (page0>>8));
773                 for(n=0;n<=max;)
774                 {
775                         len += snprintf(page + len, count - len, "\nD:  %2x > ",n);
776                         for(i=0;i<4 && n<=max;n+=4,i++)
777                                 len += snprintf(page + len, count - len,
778                                                 "%8.8x ",rtl8192_QueryBBReg(dev,(page0|n), bMaskDWord));
779                 }
780         len += snprintf(page + len, count - len,"\n");
781         *eof = 1;
782         return len;
783         }
784 static int proc_get_registers_c(char *page, char **start,
785                           off_t offset, int count,
786                           int *eof, void *data)
787 {
788         struct net_device *dev = data;
789 //      struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
790
791         int len = 0;
792         int i,n,page0;
793
794         int max=0xff;
795         page0 = 0xc00;
796
797         /* This dump the current register page */
798                 len += snprintf(page + len, count - len,
799                                 "\n####################page %x##################\n ", (page0>>8));
800                 for(n=0;n<=max;)
801                 {
802                         len += snprintf(page + len, count - len, "\nD:  %2x > ",n);
803                         for(i=0;i<4 && n<=max;n+=4,i++)
804                                 len += snprintf(page + len, count - len,
805                                                 "%8.8x ",rtl8192_QueryBBReg(dev,(page0|n), bMaskDWord));
806                 }
807         len += snprintf(page + len, count - len,"\n");
808         *eof = 1;
809         return len;
810 }
811 static int proc_get_registers_d(char *page, char **start,
812                           off_t offset, int count,
813                           int *eof, void *data)
814 {
815         struct net_device *dev = data;
816 //      struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
817
818         int len = 0;
819         int i,n,page0;
820
821         int max=0xff;
822         page0 = 0xd00;
823
824         /* This dump the current register page */
825                 len += snprintf(page + len, count - len,
826                                 "\n####################page %x##################\n ", (page0>>8));
827                 for(n=0;n<=max;)
828                 {
829                         len += snprintf(page + len, count - len, "\nD:  %2x > ",n);
830                         for(i=0;i<4 && n<=max;n+=4,i++)
831                                 len += snprintf(page + len, count - len,
832                                                 "%8.8x ",rtl8192_QueryBBReg(dev,(page0|n), bMaskDWord));
833                 }
834         len += snprintf(page + len, count - len,"\n");
835         *eof = 1;
836         return len;
837 }
838 static int proc_get_registers_e(char *page, char **start,
839                           off_t offset, int count,
840                           int *eof, void *data)
841 {
842         struct net_device *dev = data;
843 //      struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
844
845         int len = 0;
846         int i,n,page0;
847
848         int max=0xff;
849         page0 = 0xe00;
850
851         /* This dump the current register page */
852                 len += snprintf(page + len, count - len,
853                                 "\n####################page %x##################\n ", (page0>>8));
854                 for(n=0;n<=max;)
855                 {
856                         len += snprintf(page + len, count - len, "\nD:  %2x > ",n);
857                         for(i=0;i<4 && n<=max;n+=4,i++)
858                                 len += snprintf(page + len, count - len,
859                                                 "%8.8x ",rtl8192_QueryBBReg(dev,(page0|n), bMaskDWord));
860                 }
861         len += snprintf(page + len, count - len,"\n");
862         *eof = 1;
863         return len;
864 }
865
866 static int proc_get_stats_tx(char *page, char **start,
867                           off_t offset, int count,
868                           int *eof, void *data)
869 {
870         struct net_device *dev = data;
871         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
872
873         int len = 0;
874
875         len += snprintf(page + len, count - len,
876                 "TX VI priority ok int: %lu\n"
877                 "TX VI priority error int: %lu\n"
878                 "TX VO priority ok int: %lu\n"
879                 "TX VO priority error int: %lu\n"
880                 "TX BE priority ok int: %lu\n"
881                 "TX BE priority error int: %lu\n"
882                 "TX BK priority ok int: %lu\n"
883                 "TX BK priority error int: %lu\n"
884                 "TX MANAGE priority ok int: %lu\n"
885                 "TX MANAGE priority error int: %lu\n"
886                 "TX BEACON priority ok int: %lu\n"
887                 "TX BEACON priority error int: %lu\n"
888 //              "TX high priority ok int: %lu\n"
889 //              "TX high priority failed error int: %lu\n"
890                 "TX queue resume: %lu\n"
891                 "TX queue stopped?: %d\n"
892                 "TX fifo overflow: %lu\n"
893 //              "TX beacon: %lu\n"
894                 "TX VI queue: %d\n"
895                 "TX VO queue: %d\n"
896                 "TX BE queue: %d\n"
897                 "TX BK queue: %d\n"
898 //              "TX HW queue: %d\n"
899                 "TX VI dropped: %lu\n"
900                 "TX VO dropped: %lu\n"
901                 "TX BE dropped: %lu\n"
902                 "TX BK dropped: %lu\n"
903                 "TX total data packets %lu\n",
904 //              "TX beacon aborted: %lu\n",
905                 priv->stats.txviokint,
906                 priv->stats.txvierr,
907                 priv->stats.txvookint,
908                 priv->stats.txvoerr,
909                 priv->stats.txbeokint,
910                 priv->stats.txbeerr,
911                 priv->stats.txbkokint,
912                 priv->stats.txbkerr,
913                 priv->stats.txmanageokint,
914                 priv->stats.txmanageerr,
915                 priv->stats.txbeaconokint,
916                 priv->stats.txbeaconerr,
917 //              priv->stats.txhpokint,
918 //              priv->stats.txhperr,
919                 priv->stats.txresumed,
920                 netif_queue_stopped(dev),
921                 priv->stats.txoverflow,
922 //              priv->stats.txbeacon,
923                 atomic_read(&(priv->tx_pending[VI_PRIORITY])),
924                 atomic_read(&(priv->tx_pending[VO_PRIORITY])),
925                 atomic_read(&(priv->tx_pending[BE_PRIORITY])),
926                 atomic_read(&(priv->tx_pending[BK_PRIORITY])),
927 //              read_nic_byte(dev, TXFIFOCOUNT),
928                 priv->stats.txvidrop,
929                 priv->stats.txvodrop,
930                 priv->stats.txbedrop,
931                 priv->stats.txbkdrop,
932                 priv->stats.txdatapkt
933 //              priv->stats.txbeaconerr
934                 );
935
936         *eof = 1;
937         return len;
938 }
939
940
941
942 static int proc_get_stats_rx(char *page, char **start,
943                           off_t offset, int count,
944                           int *eof, void *data)
945 {
946         struct net_device *dev = data;
947         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
948
949         int len = 0;
950
951         len += snprintf(page + len, count - len,
952                 "RX packets: %lu\n"
953                 "RX urb status error: %lu\n"
954                 "RX invalid urb error: %lu\n",
955                 priv->stats.rxoktotal,
956                 priv->stats.rxstaterr,
957                 priv->stats.rxurberr);
958
959         *eof = 1;
960         return len;
961 }
962
963 void rtl8192_proc_module_init(void)
964 {
965         RT_TRACE(COMP_INIT, "Initializing proc filesystem");
966         rtl8192_proc=create_proc_entry(RTL819xU_MODULE_NAME, S_IFDIR, init_net.proc_net);
967 }
968
969
970 void rtl8192_proc_module_remove(void)
971 {
972         remove_proc_entry(RTL819xU_MODULE_NAME, init_net.proc_net);
973 }
974
975
976 void rtl8192_proc_remove_one(struct net_device *dev)
977 {
978         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
979
980
981         if (priv->dir_dev) {
982         //      remove_proc_entry("stats-hw", priv->dir_dev);
983                 remove_proc_entry("stats-tx", priv->dir_dev);
984                 remove_proc_entry("stats-rx", priv->dir_dev);
985         //      remove_proc_entry("stats-ieee", priv->dir_dev);
986                 remove_proc_entry("stats-ap", priv->dir_dev);
987                 remove_proc_entry("registers", priv->dir_dev);
988                 remove_proc_entry("registers-1", priv->dir_dev);
989                 remove_proc_entry("registers-2", priv->dir_dev);
990                 remove_proc_entry("registers-8", priv->dir_dev);
991                 remove_proc_entry("registers-9", priv->dir_dev);
992                 remove_proc_entry("registers-a", priv->dir_dev);
993                 remove_proc_entry("registers-b", priv->dir_dev);
994                 remove_proc_entry("registers-c", priv->dir_dev);
995                 remove_proc_entry("registers-d", priv->dir_dev);
996                 remove_proc_entry("registers-e", priv->dir_dev);
997         //      remove_proc_entry("cck-registers",priv->dir_dev);
998         //      remove_proc_entry("ofdm-registers",priv->dir_dev);
999                 //remove_proc_entry(dev->name, rtl8192_proc);
1000                 remove_proc_entry("wlan0", rtl8192_proc);
1001                 priv->dir_dev = NULL;
1002         }
1003 }
1004
1005
1006 void rtl8192_proc_init_one(struct net_device *dev)
1007 {
1008         struct proc_dir_entry *e;
1009         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
1010         priv->dir_dev = create_proc_entry(dev->name,
1011                                           S_IFDIR | S_IRUGO | S_IXUGO,
1012                                           rtl8192_proc);
1013         if (!priv->dir_dev) {
1014                 RT_TRACE(COMP_ERR, "Unable to initialize /proc/net/rtl8192/%s\n",
1015                       dev->name);
1016                 return;
1017         }
1018         e = create_proc_read_entry("stats-rx", S_IFREG | S_IRUGO,
1019                                    priv->dir_dev, proc_get_stats_rx, dev);
1020
1021         if (!e) {
1022                 RT_TRACE(COMP_ERR,"Unable to initialize "
1023                       "/proc/net/rtl8192/%s/stats-rx\n",
1024                       dev->name);
1025         }
1026
1027
1028         e = create_proc_read_entry("stats-tx", S_IFREG | S_IRUGO,
1029                                    priv->dir_dev, proc_get_stats_tx, dev);
1030
1031         if (!e) {
1032                 RT_TRACE(COMP_ERR, "Unable to initialize "
1033                       "/proc/net/rtl8192/%s/stats-tx\n",
1034                       dev->name);
1035         }
1036
1037         e = create_proc_read_entry("stats-ap", S_IFREG | S_IRUGO,
1038                                    priv->dir_dev, proc_get_stats_ap, dev);
1039
1040         if (!e) {
1041                 RT_TRACE(COMP_ERR, "Unable to initialize "
1042                       "/proc/net/rtl8192/%s/stats-ap\n",
1043                       dev->name);
1044         }
1045
1046         e = create_proc_read_entry("registers", S_IFREG | S_IRUGO,
1047                                    priv->dir_dev, proc_get_registers, dev);
1048         if (!e) {
1049                 RT_TRACE(COMP_ERR, "Unable to initialize "
1050                       "/proc/net/rtl8192/%s/registers\n",
1051                       dev->name);
1052         }
1053         e = create_proc_read_entry("registers-1", S_IFREG | S_IRUGO,
1054                                    priv->dir_dev, proc_get_registers_1, dev);
1055         if (!e) {
1056                 RT_TRACE(COMP_ERR, "Unable to initialize "
1057                       "/proc/net/rtl8192/%s/registers-1\n",
1058                       dev->name);
1059         }
1060         e = create_proc_read_entry("registers-2", S_IFREG | S_IRUGO,
1061                                    priv->dir_dev, proc_get_registers_2, dev);
1062         if (!e) {
1063                 RT_TRACE(COMP_ERR, "Unable to initialize "
1064                       "/proc/net/rtl8192/%s/registers-2\n",
1065                       dev->name);
1066         }
1067         e = create_proc_read_entry("registers-8", S_IFREG | S_IRUGO,
1068                                    priv->dir_dev, proc_get_registers_8, dev);
1069         if (!e) {
1070                 RT_TRACE(COMP_ERR, "Unable to initialize "
1071                       "/proc/net/rtl8192/%s/registers-8\n",
1072                       dev->name);
1073         }
1074         e = create_proc_read_entry("registers-9", S_IFREG | S_IRUGO,
1075                                    priv->dir_dev, proc_get_registers_9, dev);
1076         if (!e) {
1077                 RT_TRACE(COMP_ERR, "Unable to initialize "
1078                       "/proc/net/rtl8192/%s/registers-9\n",
1079                       dev->name);
1080         }
1081         e = create_proc_read_entry("registers-a", S_IFREG | S_IRUGO,
1082                                    priv->dir_dev, proc_get_registers_a, dev);
1083         if (!e) {
1084                 RT_TRACE(COMP_ERR, "Unable to initialize "
1085                       "/proc/net/rtl8192/%s/registers-a\n",
1086                       dev->name);
1087         }
1088         e = create_proc_read_entry("registers-b", S_IFREG | S_IRUGO,
1089                                    priv->dir_dev, proc_get_registers_b, dev);
1090         if (!e) {
1091                 RT_TRACE(COMP_ERR, "Unable to initialize "
1092                       "/proc/net/rtl8192/%s/registers-b\n",
1093                       dev->name);
1094         }
1095         e = create_proc_read_entry("registers-c", S_IFREG | S_IRUGO,
1096                                    priv->dir_dev, proc_get_registers_c, dev);
1097         if (!e) {
1098                 RT_TRACE(COMP_ERR, "Unable to initialize "
1099                       "/proc/net/rtl8192/%s/registers-c\n",
1100                       dev->name);
1101         }
1102         e = create_proc_read_entry("registers-d", S_IFREG | S_IRUGO,
1103                                    priv->dir_dev, proc_get_registers_d, dev);
1104         if (!e) {
1105                 RT_TRACE(COMP_ERR, "Unable to initialize "
1106                       "/proc/net/rtl8192/%s/registers-d\n",
1107                       dev->name);
1108         }
1109         e = create_proc_read_entry("registers-e", S_IFREG | S_IRUGO,
1110                                    priv->dir_dev, proc_get_registers_e, dev);
1111         if (!e) {
1112                 RT_TRACE(COMP_ERR, "Unable to initialize "
1113                       "/proc/net/rtl8192/%s/registers-e\n",
1114                       dev->name);
1115         }
1116 }
1117 /****************************************************************************
1118    -----------------------------MISC STUFF-------------------------
1119 *****************************************************************************/
1120
1121 /* this is only for debugging */
1122 void print_buffer(u32 *buffer, int len)
1123 {
1124         int i;
1125         u8 *buf =(u8*)buffer;
1126
1127         printk("ASCII BUFFER DUMP (len: %x):\n",len);
1128
1129         for(i=0;i<len;i++)
1130                 printk("%c",buf[i]);
1131
1132         printk("\nBINARY BUFFER DUMP (len: %x):\n",len);
1133
1134         for(i=0;i<len;i++)
1135                 printk("%x",buf[i]);
1136
1137         printk("\n");
1138 }
1139
1140 //short check_nic_enough_desc(struct net_device *dev, priority_t priority)
1141 short check_nic_enough_desc(struct net_device *dev,int queue_index)
1142 {
1143         struct r8192_priv *priv = ieee80211_priv(dev);
1144         int used = atomic_read(&priv->tx_pending[queue_index]);
1145
1146         return (used < MAX_TX_URB);
1147 }
1148
1149 void tx_timeout(struct net_device *dev)
1150 {
1151         struct r8192_priv *priv = ieee80211_priv(dev);
1152         //rtl8192_commit(dev);
1153
1154         schedule_work(&priv->reset_wq);
1155         //DMESG("TXTIMEOUT");
1156 }
1157
1158
1159 /* this is only for debug */
1160 void dump_eprom(struct net_device *dev)
1161 {
1162         int i;
1163         for(i=0; i<63; i++)
1164                 RT_TRACE(COMP_EPROM, "EEPROM addr %x : %x", i, eprom_read(dev,i));
1165 }
1166
1167 /* this is only for debug */
1168 void rtl8192_dump_reg(struct net_device *dev)
1169 {
1170         int i;
1171         int n;
1172         int max=0x1ff;
1173
1174         RT_TRACE(COMP_PHY, "Dumping NIC register map");
1175
1176         for(n=0;n<=max;)
1177         {
1178                 printk( "\nD: %2x> ", n);
1179                 for(i=0;i<16 && n<=max;i++,n++)
1180                         printk("%2x ",read_nic_byte(dev,n));
1181         }
1182         printk("\n");
1183 }
1184
1185 /****************************************************************************
1186       ------------------------------HW STUFF---------------------------
1187 *****************************************************************************/
1188
1189 void rtl8192_set_mode(struct net_device *dev,int mode)
1190 {
1191         u8 ecmd;
1192         ecmd=read_nic_byte(dev, EPROM_CMD);
1193         ecmd=ecmd &~ EPROM_CMD_OPERATING_MODE_MASK;
1194         ecmd=ecmd | (mode<<EPROM_CMD_OPERATING_MODE_SHIFT);
1195         ecmd=ecmd &~ (1<<EPROM_CS_SHIFT);
1196         ecmd=ecmd &~ (1<<EPROM_CK_SHIFT);
1197         write_nic_byte(dev, EPROM_CMD, ecmd);
1198 }
1199
1200
1201 void rtl8192_update_msr(struct net_device *dev)
1202 {
1203         struct r8192_priv *priv = ieee80211_priv(dev);
1204         u8 msr;
1205
1206         msr  = read_nic_byte(dev, MSR);
1207         msr &= ~ MSR_LINK_MASK;
1208
1209         /* do not change in link_state != WLAN_LINK_ASSOCIATED.
1210          * msr must be updated if the state is ASSOCIATING.
1211          * this is intentional and make sense for ad-hoc and
1212          * master (see the create BSS/IBSS func)
1213          */
1214         if (priv->ieee80211->state == IEEE80211_LINKED){
1215
1216                 if (priv->ieee80211->iw_mode == IW_MODE_INFRA)
1217                         msr |= (MSR_LINK_MANAGED<<MSR_LINK_SHIFT);
1218                 else if (priv->ieee80211->iw_mode == IW_MODE_ADHOC)
1219                         msr |= (MSR_LINK_ADHOC<<MSR_LINK_SHIFT);
1220                 else if (priv->ieee80211->iw_mode == IW_MODE_MASTER)
1221                         msr |= (MSR_LINK_MASTER<<MSR_LINK_SHIFT);
1222
1223         }else
1224                 msr |= (MSR_LINK_NONE<<MSR_LINK_SHIFT);
1225
1226         write_nic_byte(dev, MSR, msr);
1227 }
1228
1229 void rtl8192_set_chan(struct net_device *dev,short ch)
1230 {
1231         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
1232 //      u32 tx;
1233         RT_TRACE(COMP_CH, "=====>%s()====ch:%d\n", __FUNCTION__, ch);
1234         //printk("=====>%s()====ch:%d\n", __FUNCTION__, ch);
1235         priv->chan=ch;
1236
1237         /* this hack should avoid frame TX during channel setting*/
1238
1239
1240 //      tx = read_nic_dword(dev,TX_CONF);
1241 //      tx &= ~TX_LOOPBACK_MASK;
1242
1243 #ifndef LOOP_TEST
1244 //      write_nic_dword(dev,TX_CONF, tx |( TX_LOOPBACK_MAC<<TX_LOOPBACK_SHIFT));
1245
1246         //need to implement rf set channel here WB
1247
1248         if (priv->rf_set_chan)
1249         priv->rf_set_chan(dev,priv->chan);
1250         mdelay(10);
1251 //      write_nic_dword(dev,TX_CONF,tx | (TX_LOOPBACK_NONE<<TX_LOOPBACK_SHIFT));
1252 #endif
1253 }
1254
1255 static void rtl8192_rx_isr(struct urb *urb);
1256
1257 u32 get_rxpacket_shiftbytes_819xusb(struct ieee80211_rx_stats *pstats)
1258 {
1259
1260                 return (sizeof(rx_desc_819x_usb) + pstats->RxDrvInfoSize
1261                                 + pstats->RxBufShift);
1262
1263 }
1264 static int rtl8192_rx_initiate(struct net_device*dev)
1265 {
1266         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
1267         struct urb *entry;
1268         struct sk_buff *skb;
1269         struct rtl8192_rx_info *info;
1270
1271         /* nomal packet rx procedure */
1272         while (skb_queue_len(&priv->rx_queue) < MAX_RX_URB) {
1273                 skb = __dev_alloc_skb(RX_URB_SIZE, GFP_KERNEL);
1274                 if (!skb)
1275                         break;
1276                 entry = usb_alloc_urb(0, GFP_KERNEL);
1277                 if (!entry) {
1278                         kfree_skb(skb);
1279                         break;
1280                 }
1281 //              printk("nomal packet IN request!\n");
1282                 usb_fill_bulk_urb(entry, priv->udev,
1283                                   usb_rcvbulkpipe(priv->udev, 3), skb_tail_pointer(skb),
1284                                   RX_URB_SIZE, rtl8192_rx_isr, skb);
1285                 info = (struct rtl8192_rx_info *) skb->cb;
1286                 info->urb = entry;
1287                 info->dev = dev;
1288                 info->out_pipe = 3; //denote rx normal packet queue
1289                 skb_queue_tail(&priv->rx_queue, skb);
1290                 usb_submit_urb(entry, GFP_KERNEL);
1291         }
1292
1293         /* command packet rx procedure */
1294         while (skb_queue_len(&priv->rx_queue) < MAX_RX_URB + 3) {
1295 //              printk("command packet IN request!\n");
1296                 skb = __dev_alloc_skb(RX_URB_SIZE ,GFP_KERNEL);
1297                 if (!skb)
1298                         break;
1299                 entry = usb_alloc_urb(0, GFP_KERNEL);
1300                 if (!entry) {
1301                         kfree_skb(skb);
1302                         break;
1303                 }
1304                 usb_fill_bulk_urb(entry, priv->udev,
1305                                   usb_rcvbulkpipe(priv->udev, 9), skb_tail_pointer(skb),
1306                                   RX_URB_SIZE, rtl8192_rx_isr, skb);
1307                 info = (struct rtl8192_rx_info *) skb->cb;
1308                 info->urb = entry;
1309                 info->dev = dev;
1310                    info->out_pipe = 9; //denote rx cmd packet queue
1311                 skb_queue_tail(&priv->rx_queue, skb);
1312                 usb_submit_urb(entry, GFP_KERNEL);
1313         }
1314
1315         return 0;
1316 }
1317
1318 void rtl8192_set_rxconf(struct net_device *dev)
1319 {
1320         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
1321         u32 rxconf;
1322
1323         rxconf=read_nic_dword(dev,RCR);
1324         rxconf = rxconf &~ MAC_FILTER_MASK;
1325         rxconf = rxconf | RCR_AMF;
1326         rxconf = rxconf | RCR_ADF;
1327         rxconf = rxconf | RCR_AB;
1328         rxconf = rxconf | RCR_AM;
1329         //rxconf = rxconf | RCR_ACF;
1330
1331         if (dev->flags & IFF_PROMISC) {DMESG ("NIC in promisc mode");}
1332
1333         if(priv->ieee80211->iw_mode == IW_MODE_MONITOR || \
1334            dev->flags & IFF_PROMISC){
1335                 rxconf = rxconf | RCR_AAP;
1336         } /*else if(priv->ieee80211->iw_mode == IW_MODE_MASTER){
1337                 rxconf = rxconf | (1<<ACCEPT_ALLMAC_FRAME_SHIFT);
1338                 rxconf = rxconf | (1<<RX_CHECK_BSSID_SHIFT);
1339         }*/else{
1340                 rxconf = rxconf | RCR_APM;
1341                 rxconf = rxconf | RCR_CBSSID;
1342         }
1343
1344
1345         if(priv->ieee80211->iw_mode == IW_MODE_MONITOR){
1346                 rxconf = rxconf | RCR_AICV;
1347                 rxconf = rxconf | RCR_APWRMGT;
1348         }
1349
1350         if( priv->crcmon == 1 && priv->ieee80211->iw_mode == IW_MODE_MONITOR)
1351                 rxconf = rxconf | RCR_ACRC32;
1352
1353
1354         rxconf = rxconf &~ RX_FIFO_THRESHOLD_MASK;
1355         rxconf = rxconf | (RX_FIFO_THRESHOLD_NONE<<RX_FIFO_THRESHOLD_SHIFT);
1356         rxconf = rxconf &~ MAX_RX_DMA_MASK;
1357         rxconf = rxconf | ((u32)7<<RCR_MXDMA_OFFSET);
1358
1359 //      rxconf = rxconf | (1<<RX_AUTORESETPHY_SHIFT);
1360         rxconf = rxconf | RCR_ONLYERLPKT;
1361
1362 //      rxconf = rxconf &~ RCR_CS_MASK;
1363 //      rxconf = rxconf | (1<<RCR_CS_SHIFT);
1364
1365         write_nic_dword(dev, RCR, rxconf);
1366
1367         #ifdef DEBUG_RX
1368         DMESG("rxconf: %x %x",rxconf ,read_nic_dword(dev,RCR));
1369         #endif
1370 }
1371 //wait to be removed
1372 void rtl8192_rx_enable(struct net_device *dev)
1373 {
1374         //u8 cmd;
1375
1376         //struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
1377
1378         rtl8192_rx_initiate(dev);
1379
1380 //      rtl8192_set_rxconf(dev);
1381 }
1382
1383
1384 void rtl8192_tx_enable(struct net_device *dev)
1385 {
1386 }
1387
1388 void rtl8192_rtx_disable(struct net_device *dev)
1389 {
1390         u8 cmd;
1391         struct r8192_priv *priv = ieee80211_priv(dev);
1392         struct sk_buff *skb;
1393         struct rtl8192_rx_info *info;
1394
1395         cmd=read_nic_byte(dev,CMDR);
1396         write_nic_byte(dev, CMDR, cmd &~ \
1397                 (CR_TE|CR_RE));
1398         force_pci_posting(dev);
1399         mdelay(10);
1400
1401         while ((skb = __skb_dequeue(&priv->rx_queue))) {
1402                 info = (struct rtl8192_rx_info *) skb->cb;
1403                 if (!info->urb)
1404                         continue;
1405
1406                 usb_kill_urb(info->urb);
1407                 kfree_skb(skb);
1408         }
1409
1410         if (skb_queue_len(&priv->skb_queue)) {
1411                 printk(KERN_WARNING "skb_queue not empty\n");
1412         }
1413
1414         skb_queue_purge(&priv->skb_queue);
1415         return;
1416 }
1417
1418
1419 int alloc_tx_beacon_desc_ring(struct net_device *dev, int count)
1420 {
1421         return 0;
1422 }
1423
1424 inline u16 ieeerate2rtlrate(int rate)
1425 {
1426         switch(rate){
1427         case 10:
1428         return 0;
1429         case 20:
1430         return 1;
1431         case 55:
1432         return 2;
1433         case 110:
1434         return 3;
1435         case 60:
1436         return 4;
1437         case 90:
1438         return 5;
1439         case 120:
1440         return 6;
1441         case 180:
1442         return 7;
1443         case 240:
1444         return 8;
1445         case 360:
1446         return 9;
1447         case 480:
1448         return 10;
1449         case 540:
1450         return 11;
1451         default:
1452         return 3;
1453
1454         }
1455 }
1456 static u16 rtl_rate[] = {10,20,55,110,60,90,120,180,240,360,480,540};
1457 inline u16 rtl8192_rate2rate(short rate)
1458 {
1459         if (rate >11) return 0;
1460         return rtl_rate[rate];
1461 }
1462
1463 static void rtl8192_rx_isr(struct urb *urb)
1464 {
1465         struct sk_buff *skb = (struct sk_buff *) urb->context;
1466         struct rtl8192_rx_info *info = (struct rtl8192_rx_info *)skb->cb;
1467         struct net_device *dev = info->dev;
1468         struct r8192_priv *priv = ieee80211_priv(dev);
1469         int out_pipe = info->out_pipe;
1470         int err;
1471         if(!priv->up)
1472                 return;
1473         if (unlikely(urb->status)) {
1474                 info->urb = NULL;
1475                 priv->stats.rxstaterr++;
1476                 priv->ieee80211->stats.rx_errors++;
1477                 usb_free_urb(urb);
1478         //      printk("%s():rx status err\n",__FUNCTION__);
1479                 return;
1480         }
1481
1482         skb_unlink(skb, &priv->rx_queue);
1483         skb_put(skb, urb->actual_length);
1484
1485         skb_queue_tail(&priv->skb_queue, skb);
1486         tasklet_schedule(&priv->irq_rx_tasklet);
1487
1488         skb = dev_alloc_skb(RX_URB_SIZE);
1489         if (unlikely(!skb)) {
1490                 usb_free_urb(urb);
1491                 printk("%s():can,t alloc skb\n",__FUNCTION__);
1492                 /* TODO check rx queue length and refill *somewhere* */
1493                 return;
1494         }
1495
1496         usb_fill_bulk_urb(urb, priv->udev,
1497                         usb_rcvbulkpipe(priv->udev, out_pipe),
1498                         skb_tail_pointer(skb),
1499                         RX_URB_SIZE, rtl8192_rx_isr, skb);
1500
1501         info = (struct rtl8192_rx_info *) skb->cb;
1502         info->urb = urb;
1503         info->dev = dev;
1504         info->out_pipe = out_pipe;
1505
1506         urb->transfer_buffer = skb_tail_pointer(skb);
1507         urb->context = skb;
1508         skb_queue_tail(&priv->rx_queue, skb);
1509         err = usb_submit_urb(urb, GFP_ATOMIC);
1510         if(err && err != -EPERM)
1511                 printk("can not submit rxurb, err is %x,URB status is %x\n",err,urb->status);
1512 }
1513
1514 u32
1515 rtl819xusb_rx_command_packet(
1516         struct net_device *dev,
1517         struct ieee80211_rx_stats *pstats
1518         )
1519 {
1520         u32     status;
1521
1522         //RT_TRACE(COMP_RECV, DBG_TRACE, ("---> RxCommandPacketHandle819xUsb()\n"));
1523
1524         status = cmpk_message_handle_rx(dev, pstats);
1525         if (status)
1526         {
1527                 DMESG("rxcommandpackethandle819xusb: It is a command packet\n");
1528         }
1529         else
1530         {
1531                 //RT_TRACE(COMP_RECV, DBG_TRACE, ("RxCommandPacketHandle819xUsb: It is not a command packet\n"));
1532         }
1533
1534         //RT_TRACE(COMP_RECV, DBG_TRACE, ("<--- RxCommandPacketHandle819xUsb()\n"));
1535         return status;
1536 }
1537
1538 void rtl8192_data_hard_stop(struct net_device *dev)
1539 {
1540         //FIXME !!
1541 }
1542
1543
1544 void rtl8192_data_hard_resume(struct net_device *dev)
1545 {
1546         // FIXME !!
1547 }
1548
1549 /* this function TX data frames when the ieee80211 stack requires this.
1550  * It checks also if we need to stop the ieee tx queue, eventually do it
1551  */
1552 void rtl8192_hard_data_xmit(struct sk_buff *skb, struct net_device *dev, int rate)
1553 {
1554         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
1555         int ret;
1556         unsigned long flags;
1557         cb_desc *tcb_desc = (cb_desc *)(skb->cb + MAX_DEV_ADDR_SIZE);
1558         u8 queue_index = tcb_desc->queue_index;
1559
1560         /* shall not be referred by command packet */
1561         assert(queue_index != TXCMD_QUEUE);
1562
1563         spin_lock_irqsave(&priv->tx_lock,flags);
1564
1565         memcpy((unsigned char *)(skb->cb),&dev,sizeof(dev));
1566 //      tcb_desc->RATRIndex = 7;
1567 //      tcb_desc->bTxDisableRateFallBack = 1;
1568 //      tcb_desc->bTxUseDriverAssingedRate = 1;
1569         tcb_desc->bTxEnableFwCalcDur = 1;
1570         skb_push(skb, priv->ieee80211->tx_headroom);
1571         ret = priv->ops->rtl819x_tx(dev, skb);
1572
1573         //priv->ieee80211->stats.tx_bytes+=(skb->len - priv->ieee80211->tx_headroom);
1574         //priv->ieee80211->stats.tx_packets++;
1575
1576         spin_unlock_irqrestore(&priv->tx_lock,flags);
1577
1578 //      return ret;
1579         return;
1580 }
1581
1582 /* This is a rough attempt to TX a frame
1583  * This is called by the ieee 80211 stack to TX management frames.
1584  * If the ring is full packet are dropped (for data frame the queue
1585  * is stopped before this can happen).
1586  */
1587 int rtl8192_hard_start_xmit(struct sk_buff *skb,struct net_device *dev)
1588 {
1589         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
1590         int ret;
1591         unsigned long flags;
1592         cb_desc *tcb_desc = (cb_desc *)(skb->cb + MAX_DEV_ADDR_SIZE);
1593         u8 queue_index = tcb_desc->queue_index;
1594
1595
1596         spin_lock_irqsave(&priv->tx_lock,flags);
1597
1598         memcpy((unsigned char *)(skb->cb),&dev,sizeof(dev));
1599         if(queue_index == TXCMD_QUEUE) {
1600                 skb_push(skb, USB_HWDESC_HEADER_LEN);
1601                 priv->ops->rtl819x_tx_cmd(dev, skb);
1602                 ret = 1;
1603                 spin_unlock_irqrestore(&priv->tx_lock,flags);
1604                 return ret;
1605         } else {
1606                 skb_push(skb, priv->ieee80211->tx_headroom);
1607                 ret = priv->ops->rtl819x_tx(dev, skb);
1608         }
1609
1610         spin_unlock_irqrestore(&priv->tx_lock,flags);
1611
1612         return ret;
1613 }
1614
1615
1616 void rtl8192_try_wake_queue(struct net_device *dev, int pri);
1617
1618
1619 static void rtl8192_tx_isr(struct urb *tx_urb)
1620 {
1621         struct sk_buff *skb = (struct sk_buff*)tx_urb->context;
1622         struct net_device *dev = NULL;
1623         struct r8192_priv *priv = NULL;
1624         cb_desc *tcb_desc = (cb_desc *)(skb->cb + MAX_DEV_ADDR_SIZE);
1625         u8  queue_index = tcb_desc->queue_index;
1626 //      bool bToSend0Byte;
1627 //      u16 BufLen = skb->len;
1628
1629         memcpy(&dev,(struct net_device*)(skb->cb),sizeof(struct net_device*));
1630         priv = ieee80211_priv(dev);
1631
1632         if(tcb_desc->queue_index != TXCMD_QUEUE) {
1633                 if(tx_urb->status == 0) {
1634                 //      dev->trans_start = jiffies;
1635                         // As act as station mode, destion shall be  unicast address.
1636                         //priv->ieee80211->stats.tx_bytes+=(skb->len - priv->ieee80211->tx_headroom);
1637                         //priv->ieee80211->stats.tx_packets++;
1638                         priv->stats.txoktotal++;
1639                         priv->ieee80211->LinkDetectInfo.NumTxOkInPeriod++;
1640                         priv->stats.txbytesunicast += (skb->len - priv->ieee80211->tx_headroom);
1641                 } else {
1642                         priv->ieee80211->stats.tx_errors++;
1643                         //priv->stats.txmanageerr++;
1644                         /* TODO */
1645                 }
1646         }
1647
1648         /* free skb and tx_urb */
1649         if(skb != NULL) {
1650                 dev_kfree_skb_any(skb);
1651                 usb_free_urb(tx_urb);
1652                 atomic_dec(&priv->tx_pending[queue_index]);
1653         }
1654
1655         {
1656                 //
1657                 // Handle HW Beacon:
1658                 // We had transfer our beacon frame to host controler at this moment.
1659                 //
1660                 //
1661                 // Caution:
1662                 // Handling the wait queue of command packets.
1663                 // For Tx command packets, we must not do TCB fragment because it is not handled right now.
1664                 // We must cut the packets to match the size of TX_CMD_PKT before we send it.
1665                 //
1666         if (queue_index == MGNT_QUEUE){
1667         if (priv->ieee80211->ack_tx_to_ieee){
1668             if (rtl8192_is_tx_queue_empty(dev)){
1669                 priv->ieee80211->ack_tx_to_ieee = 0;
1670                 ieee80211_ps_tx_ack(priv->ieee80211, 1);
1671             }
1672         }
1673     }
1674                 /* Handle MPDU in wait queue. */
1675                 if(queue_index != BEACON_QUEUE) {
1676                         /* Don't send data frame during scanning.*/
1677                         if((skb_queue_len(&priv->ieee80211->skb_waitQ[queue_index]) != 0)&&\
1678                                         (!(priv->ieee80211->queue_stop))) {
1679                                 if(NULL != (skb = skb_dequeue(&(priv->ieee80211->skb_waitQ[queue_index]))))
1680                                         priv->ieee80211->softmac_hard_start_xmit(skb, dev);
1681
1682                                 return; //modified by david to avoid further processing AMSDU
1683                         }
1684                 }
1685         }
1686 }
1687
1688 void rtl8192_beacon_stop(struct net_device *dev)
1689 {
1690         u8 msr, msrm, msr2;
1691         struct r8192_priv *priv = ieee80211_priv(dev);
1692
1693         msr  = read_nic_byte(dev, MSR);
1694         msrm = msr & MSR_LINK_MASK;
1695         msr2 = msr & ~MSR_LINK_MASK;
1696
1697         if(NIC_8192U == priv->card_8192) {
1698                 usb_kill_urb(priv->rx_urb[MAX_RX_URB]);
1699         }
1700         if ((msrm == (MSR_LINK_ADHOC<<MSR_LINK_SHIFT) ||
1701                 (msrm == (MSR_LINK_MASTER<<MSR_LINK_SHIFT)))){
1702                 write_nic_byte(dev, MSR, msr2 | MSR_LINK_NONE);
1703                 write_nic_byte(dev, MSR, msr);
1704         }
1705 }
1706
1707 void rtl8192_config_rate(struct net_device* dev, u16* rate_config)
1708 {
1709          struct r8192_priv *priv = ieee80211_priv(dev);
1710          struct ieee80211_network *net;
1711          u8 i=0, basic_rate = 0;
1712          net = & priv->ieee80211->current_network;
1713
1714          for (i=0; i<net->rates_len; i++)
1715          {
1716                  basic_rate = net->rates[i]&0x7f;
1717                  switch(basic_rate)
1718                  {
1719                          case MGN_1M:   *rate_config |= RRSR_1M;        break;
1720                          case MGN_2M:   *rate_config |= RRSR_2M;        break;
1721                          case MGN_5_5M: *rate_config |= RRSR_5_5M;      break;
1722                          case MGN_11M:  *rate_config |= RRSR_11M;       break;
1723                          case MGN_6M:   *rate_config |= RRSR_6M;        break;
1724                          case MGN_9M:   *rate_config |= RRSR_9M;        break;
1725                          case MGN_12M:  *rate_config |= RRSR_12M;       break;
1726                          case MGN_18M:  *rate_config |= RRSR_18M;       break;
1727                          case MGN_24M:  *rate_config |= RRSR_24M;       break;
1728                          case MGN_36M:  *rate_config |= RRSR_36M;       break;
1729                          case MGN_48M:  *rate_config |= RRSR_48M;       break;
1730                          case MGN_54M:  *rate_config |= RRSR_54M;       break;
1731                  }
1732          }
1733          for (i=0; i<net->rates_ex_len; i++)
1734          {
1735                  basic_rate = net->rates_ex[i]&0x7f;
1736                  switch(basic_rate)
1737                  {
1738                          case MGN_1M:   *rate_config |= RRSR_1M;        break;
1739                          case MGN_2M:   *rate_config |= RRSR_2M;        break;
1740                          case MGN_5_5M: *rate_config |= RRSR_5_5M;      break;
1741                          case MGN_11M:  *rate_config |= RRSR_11M;       break;
1742                          case MGN_6M:   *rate_config |= RRSR_6M;        break;
1743                          case MGN_9M:   *rate_config |= RRSR_9M;        break;
1744                          case MGN_12M:  *rate_config |= RRSR_12M;       break;
1745                          case MGN_18M:  *rate_config |= RRSR_18M;       break;
1746                          case MGN_24M:  *rate_config |= RRSR_24M;       break;
1747                          case MGN_36M:  *rate_config |= RRSR_36M;       break;
1748                          case MGN_48M:  *rate_config |= RRSR_48M;       break;
1749                          case MGN_54M:  *rate_config |= RRSR_54M;       break;
1750                  }
1751          }
1752 }
1753
1754
1755 #define SHORT_SLOT_TIME 9
1756 #define NON_SHORT_SLOT_TIME 20
1757
1758 void rtl8192_update_cap(struct net_device* dev, u16 cap)
1759 {
1760         //u32 tmp = 0;
1761         struct r8192_priv *priv = ieee80211_priv(dev);
1762         struct ieee80211_network *net = &priv->ieee80211->current_network;
1763         priv->short_preamble = cap & WLAN_CAPABILITY_SHORT_PREAMBLE;
1764
1765         //LZM MOD 090303 HW_VAR_ACK_PREAMBLE
1766         if(0)
1767         {
1768                 u8 tmp = 0;
1769                 tmp = ((priv->nCur40MhzPrimeSC) << 5);
1770                 if (priv->short_preamble)
1771                         tmp |= 0x80;
1772                 write_nic_byte(dev, RRSR+2, tmp);
1773         }
1774
1775         if (net->mode & (IEEE_G|IEEE_N_24G))
1776         {
1777                 u8 slot_time = 0;
1778                 if ((cap & WLAN_CAPABILITY_SHORT_SLOT)&&(!priv->ieee80211->pHTInfo->bCurrentRT2RTLongSlotTime))
1779                 {//short slot time
1780                         slot_time = SHORT_SLOT_TIME;
1781                 }
1782                 else //long slot time
1783                         slot_time = NON_SHORT_SLOT_TIME;
1784                 priv->slot_time = slot_time;
1785                 write_nic_byte(dev, SLOT_TIME, slot_time);
1786         }
1787
1788 }
1789 void rtl8192_net_update(struct net_device *dev)
1790 {
1791
1792         struct r8192_priv *priv = ieee80211_priv(dev);
1793         struct ieee80211_network *net;
1794         u16 BcnTimeCfg = 0, BcnCW = 6, BcnIFS = 0xf;
1795         u16 rate_config = 0;
1796         net = & priv->ieee80211->current_network;
1797
1798         rtl8192_config_rate(dev, &rate_config);
1799         priv->basic_rate = rate_config &= 0x15f;
1800
1801         write_nic_dword(dev,BSSIDR,((u32*)net->bssid)[0]);
1802         write_nic_word(dev,BSSIDR+4,((u16*)net->bssid)[2]);
1803         //for(i=0;i<ETH_ALEN;i++)
1804         //      write_nic_byte(dev,BSSID+i,net->bssid[i]);
1805
1806         rtl8192_update_msr(dev);
1807 //      rtl8192_update_cap(dev, net->capability);
1808         if (priv->ieee80211->iw_mode == IW_MODE_ADHOC)
1809         {
1810         write_nic_word(dev, ATIMWND, 2);
1811         write_nic_word(dev, BCN_DMATIME, 1023);
1812         write_nic_word(dev, BCN_INTERVAL, net->beacon_interval);
1813 //      write_nic_word(dev, BcnIntTime, 100);
1814         write_nic_word(dev, BCN_DRV_EARLY_INT, 1);
1815         write_nic_byte(dev, BCN_ERR_THRESH, 100);
1816                 BcnTimeCfg |= (BcnCW<<BCN_TCFG_CW_SHIFT);
1817         // TODO: BcnIFS may required to be changed on ASIC
1818                 BcnTimeCfg |= BcnIFS<<BCN_TCFG_IFS;
1819
1820         write_nic_word(dev, BCN_TCFG, BcnTimeCfg);
1821         }
1822
1823
1824
1825 }
1826
1827 //temporary hw beacon is not used any more.
1828 //open it when necessary
1829 #if 1
1830 void rtl819xusb_beacon_tx(struct net_device *dev,u16  tx_rate)
1831 {
1832 }
1833 #endif
1834 inline u8 rtl8192_IsWirelessBMode(u16 rate)
1835 {
1836         if( ((rate <= 110) && (rate != 60) && (rate != 90)) || (rate == 220) )
1837                 return 1;
1838         else return 0;
1839 }
1840
1841 u16 N_DBPSOfRate(u16 DataRate);
1842
1843 u16 ComputeTxTime(
1844         u16             FrameLength,
1845         u16             DataRate,
1846         u8              bManagementFrame,
1847         u8              bShortPreamble
1848 )
1849 {
1850         u16     FrameTime;
1851         u16     N_DBPS;
1852         u16     Ceiling;
1853
1854         if( rtl8192_IsWirelessBMode(DataRate) )
1855         {
1856                 if( bManagementFrame || !bShortPreamble || DataRate == 10 )
1857                 {       // long preamble
1858                         FrameTime = (u16)(144+48+(FrameLength*8/(DataRate/10)));
1859                 }
1860                 else
1861                 {       // Short preamble
1862                         FrameTime = (u16)(72+24+(FrameLength*8/(DataRate/10)));
1863                 }
1864                 if( ( FrameLength*8 % (DataRate/10) ) != 0 ) //Get the Ceilling
1865                                 FrameTime ++;
1866         } else {        //802.11g DSSS-OFDM PLCP length field calculation.
1867                 N_DBPS = N_DBPSOfRate(DataRate);
1868                 Ceiling = (16 + 8*FrameLength + 6) / N_DBPS
1869                                 + (((16 + 8*FrameLength + 6) % N_DBPS) ? 1 : 0);
1870                 FrameTime = (u16)(16 + 4 + 4*Ceiling + 6);
1871         }
1872         return FrameTime;
1873 }
1874
1875 u16 N_DBPSOfRate(u16 DataRate)
1876 {
1877          u16 N_DBPS = 24;
1878
1879          switch(DataRate)
1880          {
1881          case 60:
1882           N_DBPS = 24;
1883           break;
1884
1885          case 90:
1886           N_DBPS = 36;
1887           break;
1888
1889          case 120:
1890           N_DBPS = 48;
1891           break;
1892
1893          case 180:
1894           N_DBPS = 72;
1895           break;
1896
1897          case 240:
1898           N_DBPS = 96;
1899           break;
1900
1901          case 360:
1902           N_DBPS = 144;
1903           break;
1904
1905          case 480:
1906           N_DBPS = 192;
1907           break;
1908
1909          case 540:
1910           N_DBPS = 216;
1911           break;
1912
1913          default:
1914           break;
1915          }
1916
1917          return N_DBPS;
1918 }
1919
1920 void rtl819xU_cmd_isr(struct urb *tx_cmd_urb, struct pt_regs *regs)
1921 {
1922         usb_free_urb(tx_cmd_urb);
1923 }
1924
1925 unsigned int txqueue2outpipe(struct r8192_priv* priv,unsigned int tx_queue) {
1926
1927         if(tx_queue >= 9)
1928         {
1929                 RT_TRACE(COMP_ERR,"%s():Unknown queue ID!!!\n",__FUNCTION__);
1930                 return 0x04;
1931         }
1932         return priv->txqueue_to_outpipemap[tx_queue];
1933 }
1934
1935 short rtl8192SU_tx_cmd(struct net_device *dev, struct sk_buff *skb)
1936 {
1937         struct r8192_priv *priv = ieee80211_priv(dev);
1938         int                     status;
1939         struct urb              *tx_urb;
1940         unsigned int            idx_pipe;
1941         tx_desc_cmd_819x_usb *pdesc = (tx_desc_cmd_819x_usb *)skb->data;
1942         cb_desc *tcb_desc = (cb_desc *)(skb->cb + MAX_DEV_ADDR_SIZE);
1943         u8 queue_index = tcb_desc->queue_index;
1944         u32                     PktSize = 0;
1945
1946         //printk("\n %s::::::::::::::::::::::queue_index = %d\n",__FUNCTION__, queue_index);
1947         atomic_inc(&priv->tx_pending[queue_index]);
1948
1949         tx_urb = usb_alloc_urb(0,GFP_ATOMIC);
1950         if(!tx_urb){
1951                 dev_kfree_skb(skb);
1952                 return -ENOMEM;
1953         }
1954
1955         memset(pdesc, 0, USB_HWDESC_HEADER_LEN);
1956
1957         /* Tx descriptor ought to be set according to the skb->cb */
1958         pdesc->LINIP = tcb_desc->bLastIniPkt;
1959         PktSize = (u16)(skb->len - USB_HWDESC_HEADER_LEN);
1960         pdesc->PktSize = PktSize;
1961         //printk("PKTSize = %d %x\n",pdesc->PktSize,pdesc->PktSize);
1962         //----------------------------------------------------------------------------
1963         // Fill up USB_OUT_CONTEXT.
1964         //----------------------------------------------------------------------------
1965         // Get index to out pipe from specified QueueID.
1966         idx_pipe = txqueue2outpipe(priv,queue_index);
1967         //printk("=============>%s queue_index:%d, outpipe:%d\n", __func__,queue_index,priv->RtOutPipes[idx_pipe]);
1968
1969         usb_fill_bulk_urb(tx_urb,
1970                                     priv->udev,
1971                                     usb_sndbulkpipe(priv->udev,priv->RtOutPipes[idx_pipe]),
1972                                     skb->data,
1973                                     skb->len,
1974                                     rtl8192_tx_isr,
1975                                     skb);
1976
1977         status = usb_submit_urb(tx_urb, GFP_ATOMIC);
1978         if (!status){
1979                 return 0;
1980         }else{
1981                 printk("Error TX CMD URB, error %d",
1982                                 status);
1983                 return -1;
1984         }
1985 }
1986
1987 /*
1988  * Mapping Software/Hardware descriptor queue id to "Queue Select Field"
1989  * in TxFwInfo data structure
1990  * 2006.10.30 by Emily
1991  *
1992  * \param QUEUEID       Software Queue
1993 */
1994 u8 MapHwQueueToFirmwareQueue(u8 QueueID)
1995 {
1996         u8 QueueSelect = 0x0;       //defualt set to
1997
1998         switch(QueueID) {
1999                 case BE_QUEUE:
2000                         QueueSelect = QSLT_BE;  //or QSelect = pTcb->priority;
2001                         break;
2002
2003                 case BK_QUEUE:
2004                         QueueSelect = QSLT_BK;  //or QSelect = pTcb->priority;
2005                         break;
2006
2007                 case VO_QUEUE:
2008                         QueueSelect = QSLT_VO;  //or QSelect = pTcb->priority;
2009                         break;
2010
2011                 case VI_QUEUE:
2012                         QueueSelect = QSLT_VI;  //or QSelect = pTcb->priority;
2013                         break;
2014                 case MGNT_QUEUE:
2015                         QueueSelect = QSLT_MGNT;
2016                         break;
2017
2018                 case BEACON_QUEUE:
2019                         QueueSelect = QSLT_BEACON;
2020                         break;
2021
2022                         // TODO: 2006.10.30 mark other queue selection until we verify it is OK
2023                         // TODO: Remove Assertions
2024 //#if (RTL819X_FPGA_VER & RTL819X_FPGA_GUANGAN_070502)
2025                 case TXCMD_QUEUE:
2026                         QueueSelect = QSLT_CMD;
2027                         break;
2028 //#endif
2029                 case HIGH_QUEUE:
2030                         QueueSelect = QSLT_HIGH;
2031                         break;
2032
2033                 default:
2034                         RT_TRACE(COMP_ERR, "TransmitTCB(): Impossible Queue Selection: %d \n", QueueID);
2035                         break;
2036         }
2037         return QueueSelect;
2038 }
2039
2040 u8 MRateToHwRate8190Pci(u8 rate)
2041 {
2042         u8      ret = DESC92S_RATE1M;
2043
2044         switch(rate)
2045         {
2046                 // CCK and OFDM non-HT rates
2047         case MGN_1M:            ret = DESC92S_RATE1M;   break;
2048         case MGN_2M:            ret = DESC92S_RATE2M;   break;
2049         case MGN_5_5M:          ret = DESC92S_RATE5_5M; break;
2050         case MGN_11M:           ret = DESC92S_RATE11M;  break;
2051         case MGN_6M:            ret = DESC92S_RATE6M;   break;
2052         case MGN_9M:            ret = DESC92S_RATE9M;   break;
2053         case MGN_12M:           ret = DESC92S_RATE12M;  break;
2054         case MGN_18M:           ret = DESC92S_RATE18M;  break;
2055         case MGN_24M:           ret = DESC92S_RATE24M;  break;
2056         case MGN_36M:           ret = DESC92S_RATE36M;  break;
2057         case MGN_48M:           ret = DESC92S_RATE48M;  break;
2058         case MGN_54M:           ret = DESC92S_RATE54M;  break;
2059
2060                 // HT rates since here
2061         case MGN_MCS0:          ret = DESC92S_RATEMCS0; break;
2062         case MGN_MCS1:          ret = DESC92S_RATEMCS1; break;
2063         case MGN_MCS2:          ret = DESC92S_RATEMCS2; break;
2064         case MGN_MCS3:          ret = DESC92S_RATEMCS3; break;
2065         case MGN_MCS4:          ret = DESC92S_RATEMCS4; break;
2066         case MGN_MCS5:          ret = DESC92S_RATEMCS5; break;
2067         case MGN_MCS6:          ret = DESC92S_RATEMCS6; break;
2068         case MGN_MCS7:          ret = DESC92S_RATEMCS7; break;
2069         case MGN_MCS8:          ret = DESC92S_RATEMCS8; break;
2070         case MGN_MCS9:          ret = DESC92S_RATEMCS9; break;
2071         case MGN_MCS10: ret = DESC92S_RATEMCS10;        break;
2072         case MGN_MCS11: ret = DESC92S_RATEMCS11;        break;
2073         case MGN_MCS12: ret = DESC92S_RATEMCS12;        break;
2074         case MGN_MCS13: ret = DESC92S_RATEMCS13;        break;
2075         case MGN_MCS14: ret = DESC92S_RATEMCS14;        break;
2076         case MGN_MCS15: ret = DESC92S_RATEMCS15;        break;
2077
2078         // Set the highest SG rate
2079         case MGN_MCS0_SG:
2080         case MGN_MCS1_SG:
2081         case MGN_MCS2_SG:
2082         case MGN_MCS3_SG:
2083         case MGN_MCS4_SG:
2084         case MGN_MCS5_SG:
2085         case MGN_MCS6_SG:
2086         case MGN_MCS7_SG:
2087         case MGN_MCS8_SG:
2088         case MGN_MCS9_SG:
2089         case MGN_MCS10_SG:
2090         case MGN_MCS11_SG:
2091         case MGN_MCS12_SG:
2092         case MGN_MCS13_SG:
2093         case MGN_MCS14_SG:
2094         case MGN_MCS15_SG:
2095         {
2096                 ret = DESC92S_RATEMCS15_SG;
2097                 break;
2098         }
2099
2100         default:                break;
2101         }
2102         return ret;
2103 }
2104
2105 u8 QueryIsShort(u8 TxHT, u8 TxRate, cb_desc *tcb_desc)
2106 {
2107         u8   tmp_Short;
2108
2109         tmp_Short = (TxHT==1)?((tcb_desc->bUseShortGI)?1:0):((tcb_desc->bUseShortPreamble)?1:0);
2110
2111         if(TxHT==1 && TxRate != DESC90_RATEMCS15)
2112                 tmp_Short = 0;
2113
2114         return tmp_Short;
2115 }
2116
2117 static void tx_zero_isr(struct urb *tx_urb)
2118 {
2119         return;
2120 }
2121
2122
2123 /*
2124  * The tx procedure is just as following,  skb->cb will contain all the following
2125  *information: * priority, morefrag, rate, &dev.
2126  * */
2127  //     <Note> Buffer format for 8192S Usb bulk out:
2128 //
2129 //  --------------------------------------------------
2130 //  | 8192S Usb Tx Desc | 802_11_MAC_header |    data          |
2131 //  --------------------------------------------------
2132 //  |  32 bytes                   |       24 bytes             |0-2318 bytes|
2133 //  --------------------------------------------------
2134 //  |<------------ BufferLen ------------------------->|
2135
2136 short rtl8192SU_tx(struct net_device *dev, struct sk_buff* skb)
2137 {
2138         struct r8192_priv *priv = ieee80211_priv(dev);
2139         cb_desc *tcb_desc = (cb_desc *)(skb->cb + MAX_DEV_ADDR_SIZE);
2140         tx_desc_819x_usb *tx_desc = (tx_desc_819x_usb *)skb->data;
2141         //tx_fwinfo_819x_usb *tx_fwinfo = (tx_fwinfo_819x_usb *)(skb->data + USB_HWDESC_HEADER_LEN);//92su del
2142         struct usb_device *udev = priv->udev;
2143         int pend;
2144         int status;
2145         struct urb *tx_urb = NULL, *tx_urb_zero = NULL;
2146         //int urb_len;
2147         unsigned int idx_pipe;
2148         u16             MPDUOverhead = 0;
2149         //RT_DEBUG_DATA(COMP_SEND, tcb_desc, sizeof(cb_desc));
2150
2151         pend = atomic_read(&priv->tx_pending[tcb_desc->queue_index]);
2152         /* we are locked here so the two atomic_read and inc are executed
2153          * without interleaves  * !!! For debug purpose           */
2154         if( pend > MAX_TX_URB){
2155                 switch (tcb_desc->queue_index) {
2156                         case VO_PRIORITY:
2157                                 priv->stats.txvodrop++;
2158                                 break;
2159                         case VI_PRIORITY:
2160                                 priv->stats.txvidrop++;
2161                                 break;
2162                         case BE_PRIORITY:
2163                                 priv->stats.txbedrop++;
2164                                 break;
2165                         default://BK_PRIORITY
2166                                 priv->stats.txbkdrop++;
2167                                 break;
2168                 }
2169                 printk("To discard skb packet!\n");
2170                 dev_kfree_skb_any(skb);
2171                 return -1;
2172         }
2173
2174         tx_urb = usb_alloc_urb(0,GFP_ATOMIC);
2175         if(!tx_urb){
2176                 dev_kfree_skb_any(skb);
2177                 return -ENOMEM;
2178         }
2179
2180         memset(tx_desc, 0, sizeof(tx_desc_819x_usb));
2181
2182
2183                 tx_desc->NonQos = (IsQoSDataFrame(skb->data)==TRUE)? 0:1;
2184
2185         /* Fill Tx descriptor */
2186         //memset(tx_fwinfo,0,sizeof(tx_fwinfo_819x_usb));
2187
2188         // This part can just fill to the first descriptor of the frame.
2189         /* DWORD 0 */
2190         tx_desc->TxHT = (tcb_desc->data_rate&0x80)?1:0;
2191
2192
2193         tx_desc->TxRate = MRateToHwRate8190Pci(tcb_desc->data_rate);
2194         //tx_desc->EnableCPUDur = tcb_desc->bTxEnableFwCalcDur;
2195         tx_desc->TxShort = QueryIsShort(tx_desc->TxHT, tx_desc->TxRate, tcb_desc);
2196
2197
2198         // Aggregation related
2199         if(tcb_desc->bAMPDUEnable) {//AMPDU enabled
2200                 tx_desc->AllowAggregation = 1;
2201                 /* DWORD 1 */
2202                 //tx_fwinfo->RxMF = tcb_desc->ampdu_factor;
2203                 //tx_fwinfo->RxAMD = tcb_desc->ampdu_density&0x07;//ampdudensity
2204         } else {
2205                 tx_desc->AllowAggregation = 0;
2206                 /* DWORD 1 */
2207                 //tx_fwinfo->RxMF = 0;
2208                 //tx_fwinfo->RxAMD = 0;
2209         }
2210
2211         //
2212         // <Roger_Notes> For AMPDU case, we must insert SSN into TX_DESC,
2213         // FW according as this SSN to do necessary packet retry.
2214         // 2008.06.06.
2215         //
2216         {
2217                 u8      *pSeq;
2218                 u16     Temp;
2219                 //pSeq = (u8 *)(VirtualAddress+USB_HWDESC_HEADER_LEN + FRAME_OFFSET_SEQUENCE);
2220                 pSeq = (u8 *)(skb->data+USB_HWDESC_HEADER_LEN + 22);
2221                 Temp = pSeq[0];
2222                 Temp <<= 12;
2223                 Temp |= (*(u16 *)pSeq)>>4;
2224                 tx_desc->Seq = Temp;
2225         }
2226
2227         /* Protection mode related */
2228         tx_desc->RTSEn = (tcb_desc->bRTSEnable)?1:0;
2229         tx_desc->CTS2Self = (tcb_desc->bCTSEnable)?1:0;
2230         tx_desc->RTSSTBC = (tcb_desc->bRTSSTBC)?1:0;
2231         tx_desc->RTSHT = (tcb_desc->rts_rate&0x80)?1:0;
2232         tx_desc->RTSRate =  MRateToHwRate8190Pci((u8)tcb_desc->rts_rate);
2233         tx_desc->RTSSubcarrier = (tx_desc->RTSHT==0)?(tcb_desc->RTSSC):0;
2234         tx_desc->RTSBW = (tx_desc->RTSHT==1)?((tcb_desc->bRTSBW)?1:0):0;
2235         tx_desc->RTSShort = (tx_desc->RTSHT==0)?(tcb_desc->bRTSUseShortPreamble?1:0):\
2236                                 (tcb_desc->bRTSUseShortGI?1:0);
2237         //LZM 090219
2238         tx_desc->DisRTSFB = 0;
2239         tx_desc->RTSRateFBLmt = 0xf;
2240
2241         // <Roger_EXP> 2008.09.22. We disable RTS rate fallback temporarily.
2242         //tx_desc->DisRTSFB = 0x01;
2243
2244         /* Set Bandwidth and sub-channel settings. */
2245         if(priv->CurrentChannelBW == HT_CHANNEL_WIDTH_20_40)
2246         {
2247                 if(tcb_desc->bPacketBW) {
2248                         tx_desc->TxBandwidth = 1;
2249                         tx_desc->TxSubCarrier = 0;    //By SD3's Jerry suggestion, use duplicated mode
2250                 } else {
2251                         tx_desc->TxBandwidth = 0;
2252                         tx_desc->TxSubCarrier = priv->nCur40MhzPrimeSC;
2253                 }
2254         } else {
2255                 tx_desc->TxBandwidth = 0;
2256                 tx_desc->TxSubCarrier = 0;
2257         }
2258
2259
2260         //memset(tx_desc, 0, sizeof(tx_desc_819x_usb));
2261         /* DWORD 0 */
2262         tx_desc->LINIP = 0;
2263         //tx_desc->CmdInit = 1; //92su del
2264         tx_desc->Offset =  USB_HWDESC_HEADER_LEN;
2265
2266         {
2267                 tx_desc->PktSize = (skb->len - USB_HWDESC_HEADER_LEN) & 0xffff;
2268         }
2269
2270         /*DWORD 1*/
2271         //tx_desc->SecCAMID= 0;//92su del
2272         tx_desc->RaBRSRID= tcb_desc->RATRIndex;
2273 //#ifdef RTL8192S_PREPARE_FOR_NORMAL_RELEASE
2274
2275         {
2276                 MPDUOverhead = 0;
2277                 //tx_desc->NoEnc = 1;//92su del
2278         }
2279
2280         tx_desc->SecType = 0x0;
2281
2282                 if (tcb_desc->bHwSec)
2283                         {
2284                                 switch (priv->ieee80211->pairwise_key_type)
2285                                 {
2286                                         case KEY_TYPE_WEP40:
2287                                         case KEY_TYPE_WEP104:
2288                                                  tx_desc->SecType = 0x1;
2289                                                  //tx_desc->NoEnc = 0;//92su del
2290                                                  break;
2291                                         case KEY_TYPE_TKIP:
2292                                                  tx_desc->SecType = 0x2;
2293                                                  //tx_desc->NoEnc = 0;//92su del
2294                                                  break;
2295                                         case KEY_TYPE_CCMP:
2296                                                  tx_desc->SecType = 0x3;
2297                                                  //tx_desc->NoEnc = 0;//92su del
2298                                                  break;
2299                                         case KEY_TYPE_NA:
2300                                                  tx_desc->SecType = 0x0;
2301                                                  //tx_desc->NoEnc = 1;//92su del
2302                                                  break;
2303                                         default:
2304                                                  tx_desc->SecType = 0x0;
2305                                                  //tx_desc->NoEnc = 1;//92su del
2306                                                  break;
2307                                 }
2308                         }
2309
2310         //tx_desc->TxFWInfoSize =  sizeof(tx_fwinfo_819x_usb);//92su del
2311
2312
2313         tx_desc->USERATE = tcb_desc->bTxUseDriverAssingedRate;
2314         tx_desc->DISFB = tcb_desc->bTxDisableRateFallBack;
2315         tx_desc->DataRateFBLmt = 0x1F;// Alwasy enable all rate fallback range
2316
2317         tx_desc->QueueSelect = MapHwQueueToFirmwareQueue(tcb_desc->queue_index);
2318
2319
2320         /* Fill fields that are required to be initialized in all of the descriptors */
2321         //DWORD 0
2322         tx_desc->FirstSeg = 1;
2323         tx_desc->LastSeg = 1;
2324         tx_desc->OWN = 1;
2325
2326         {
2327                 //DWORD 2
2328                 //tx_desc->TxBufferSize = (u32)(skb->len - USB_HWDESC_HEADER_LEN);
2329                 tx_desc->TxBufferSize = (u32)(skb->len);//92su mod FIXLZM
2330         }
2331
2332         /* Get index to out pipe from specified QueueID */
2333         idx_pipe = txqueue2outpipe(priv,tcb_desc->queue_index);
2334         //printk("=============>%s queue_index:%d, outpipe:%d\n", __func__,tcb_desc->queue_index,priv->RtOutPipes[idx_pipe]);
2335
2336         //RT_DEBUG_DATA(COMP_SEND,tx_fwinfo,sizeof(tx_fwinfo_819x_usb));
2337         //RT_DEBUG_DATA(COMP_SEND,tx_desc,sizeof(tx_desc_819x_usb));
2338
2339         /* To submit bulk urb */
2340         usb_fill_bulk_urb(tx_urb,
2341                                     udev,
2342                                     usb_sndbulkpipe(udev,priv->RtOutPipes[idx_pipe]),
2343                                     skb->data,
2344                                     skb->len, rtl8192_tx_isr, skb);
2345
2346         status = usb_submit_urb(tx_urb, GFP_ATOMIC);
2347         if (!status) {
2348                 /*
2349                  * we need to send 0 byte packet whenever 512N bytes/64N(HIGN SPEED/NORMAL SPEED) bytes packet has been transmitted.
2350                  * Otherwise, it will be halt to wait for another packet. WB. 2008.08.27
2351                  */
2352                 bool bSend0Byte = false;
2353                 u8 zero = 0;
2354                 if(udev->speed == USB_SPEED_HIGH) {
2355                         if (skb->len > 0 && skb->len % 512 == 0)
2356                                 bSend0Byte = true;
2357                 }
2358                 else {
2359                         if (skb->len > 0 && skb->len % 64 == 0)
2360                                 bSend0Byte = true;
2361                 }
2362                 if (bSend0Byte) {
2363                         tx_urb_zero = usb_alloc_urb(0,GFP_ATOMIC);
2364                         if(!tx_urb_zero) {
2365                                 RT_TRACE(COMP_ERR, "can't alloc urb for zero byte\n");
2366                                 return -ENOMEM;
2367                         }
2368                         usb_fill_bulk_urb(tx_urb_zero,udev,
2369                                         usb_sndbulkpipe(udev,idx_pipe), &zero,
2370                                         0, tx_zero_isr, dev);
2371                         status = usb_submit_urb(tx_urb_zero, GFP_ATOMIC);
2372                         switch (status) {
2373                                 case 0:
2374                                         break;
2375                                 case -ECONNRESET:
2376                                 case -ENOENT:
2377                                 case -ESHUTDOWN:
2378                                         break;
2379                                 default:
2380                                         RT_TRACE(COMP_ERR, "Error TX URB for zero byte %d, error %d",
2381                                                 atomic_read(&priv->tx_pending[tcb_desc->queue_index]), status);
2382                                         return -1;
2383                         }
2384                 }
2385                 dev->trans_start = jiffies;
2386                 atomic_inc(&priv->tx_pending[tcb_desc->queue_index]);
2387                 return 0;
2388         } else {
2389                 RT_TRACE(COMP_ERR, "Error TX URB %d, error %d", atomic_read(&priv->tx_pending[tcb_desc->queue_index]),
2390                                 status);
2391                 return -1;
2392         }
2393 }
2394
2395 void rtl8192SU_net_update(struct net_device *dev)
2396 {
2397
2398         struct r8192_priv *priv = ieee80211_priv(dev);
2399         struct ieee80211_device* ieee = priv->ieee80211;
2400         struct ieee80211_network *net = &priv->ieee80211->current_network;
2401         //u16 BcnTimeCfg = 0, BcnCW = 6, BcnIFS = 0xf;
2402         u16 rate_config = 0;
2403         u32 regTmp = 0;
2404         u8 rateIndex = 0;
2405         u8      retrylimit = 0x30;
2406         u16 cap = net->capability;
2407
2408         priv->short_preamble = cap & WLAN_CAPABILITY_SHORT_PREAMBLE;
2409
2410 //HW_VAR_BASIC_RATE
2411         //update Basic rate: RR, BRSR
2412         rtl8192_config_rate(dev, &rate_config); //HalSetBrateCfg
2413
2414         priv->basic_rate = rate_config  = rate_config & 0x15f;
2415
2416         // Set RRSR rate table.
2417         write_nic_byte(dev, RRSR, rate_config&0xff);
2418         write_nic_byte(dev, RRSR+1, (rate_config>>8)&0xff);
2419
2420         // Set RTS initial rate
2421         while(rate_config > 0x1)
2422         {
2423                 rate_config = (rate_config>> 1);
2424                 rateIndex++;
2425         }
2426         write_nic_byte(dev, INIRTSMCS_SEL, rateIndex);
2427 //HW_VAR_BASIC_RATE
2428
2429         //set ack preample
2430         regTmp = (priv->nCur40MhzPrimeSC) << 5;
2431         if (priv->short_preamble)
2432                 regTmp |= 0x80;
2433         write_nic_byte(dev, RRSR+2, regTmp);
2434
2435         write_nic_dword(dev,BSSIDR,((u32*)net->bssid)[0]);
2436         write_nic_word(dev,BSSIDR+4,((u16*)net->bssid)[2]);
2437
2438         write_nic_word(dev, BCN_INTERVAL, net->beacon_interval);
2439         //2008.10.24 added by tynli for beacon changed.
2440         PHY_SetBeaconHwReg( dev, net->beacon_interval);
2441
2442         rtl8192_update_cap(dev, cap);
2443
2444         if (ieee->iw_mode == IW_MODE_ADHOC){
2445                 retrylimit = 7;
2446                 //we should enable ibss interrupt here, but disable it temporarily
2447                 if (0){
2448                         priv->irq_mask |= (IMR_BcnInt | IMR_BcnInt | IMR_TBDOK | IMR_TBDER);
2449                         //rtl8192_irq_disable(dev);
2450                         //rtl8192_irq_enable(dev);
2451                 }
2452         }
2453         else{
2454                 if (0){
2455                         priv->irq_mask &= ~(IMR_BcnInt | IMR_BcnInt | IMR_TBDOK | IMR_TBDER);
2456                         //rtl8192_irq_disable(dev);
2457                         //rtl8192_irq_enable(dev);
2458                 }
2459         }
2460
2461         priv->ShortRetryLimit = priv->LongRetryLimit = retrylimit;
2462
2463         write_nic_word(dev,     RETRY_LIMIT,
2464                                 retrylimit << RETRY_LIMIT_SHORT_SHIFT | \
2465                                 retrylimit << RETRY_LIMIT_LONG_SHIFT);
2466 }
2467
2468 void rtl8192SU_update_ratr_table(struct net_device* dev)
2469 {
2470                 struct r8192_priv* priv = ieee80211_priv(dev);
2471         struct ieee80211_device* ieee = priv->ieee80211;
2472         u8* pMcsRate = ieee->dot11HTOperationalRateSet;
2473         //struct ieee80211_network *net = &ieee->current_network;
2474         u32 ratr_value = 0;
2475
2476         u8 rate_index = 0;
2477         int WirelessMode = ieee->mode;
2478         u8 MimoPs = ieee->pHTInfo->PeerMimoPs;
2479
2480         u8 bNMode = 0;
2481
2482         rtl8192_config_rate(dev, (u16*)(&ratr_value));
2483         ratr_value |= (*(u16*)(pMcsRate)) << 12;
2484
2485         //switch (ieee->mode)
2486         switch (WirelessMode)
2487         {
2488                 case IEEE_A:
2489                         ratr_value &= 0x00000FF0;
2490                         break;
2491                 case IEEE_B:
2492                         ratr_value &= 0x0000000D;
2493                         break;
2494                 case IEEE_G:
2495                         ratr_value &= 0x00000FF5;
2496                         break;
2497                 case IEEE_N_24G:
2498                 case IEEE_N_5G:
2499                 {
2500                         bNMode = 1;
2501
2502                         if (MimoPs == 0) //MIMO_PS_STATIC
2503                                         {
2504                                 ratr_value &= 0x0007F005;
2505                         }
2506                         else
2507                         {       // MCS rate only => for 11N mode.
2508                                 u32     ratr_mask;
2509
2510                                 // 1T2R or 1T1R, Spatial Stream 2 should be disabled
2511                                 if (    priv->rf_type == RF_1T2R ||
2512                                         priv->rf_type == RF_1T1R ||
2513                                         (ieee->pHTInfo->IOTAction & HT_IOT_ACT_DISABLE_TX_2SS) )
2514                                                 ratr_mask = 0x000ff005;
2515                                         else
2516                                                 ratr_mask = 0x0f0ff005;
2517
2518                                 if((ieee->pHTInfo->bCurTxBW40MHz) &&
2519                                     !(ieee->pHTInfo->IOTAction & HT_IOT_ACT_DISABLE_TX_40_MHZ))
2520                                         ratr_mask |= 0x00000010; // Set 6MBps
2521
2522                                 // Select rates for rate adaptive mechanism.
2523                                         ratr_value &= ratr_mask;
2524                                         }
2525                         }
2526                         break;
2527                 default:
2528                         if(0)
2529                         {
2530                                 if(priv->rf_type == RF_1T2R)    // 1T2R, Spatial Stream 2 should be disabled
2531                                 {
2532                                 ratr_value &= 0x000ff0f5;
2533                                 }
2534                                 else
2535                                 {
2536                                 ratr_value &= 0x0f0ff0f5;
2537                                 }
2538                         }
2539                         //printk("====>%s(), mode is not correct:%x\n", __FUNCTION__, ieee->mode);
2540                         break;
2541         }
2542
2543         ratr_value &= 0x0FFFFFFF;
2544
2545         // Get MAX MCS available.
2546         if (   (bNMode && ((ieee->pHTInfo->IOTAction & HT_IOT_ACT_DISABLE_SHORT_GI)==0)) &&
2547                 ((ieee->pHTInfo->bCurBW40MHz && ieee->pHTInfo->bCurShortGI40MHz) ||
2548                 (!ieee->pHTInfo->bCurBW40MHz && ieee->pHTInfo->bCurShortGI20MHz)))
2549         {
2550                 u8 shortGI_rate = 0;
2551                 u32 tmp_ratr_value = 0;
2552                 ratr_value |= 0x10000000;//???
2553                 tmp_ratr_value = (ratr_value>>12);
2554                 for(shortGI_rate=15; shortGI_rate>0; shortGI_rate--)
2555                 {
2556                         if((1<<shortGI_rate) & tmp_ratr_value)
2557                                 break;
2558                 }
2559                 shortGI_rate = (shortGI_rate<<12)|(shortGI_rate<<8)|(shortGI_rate<<4)|(shortGI_rate);
2560                 write_nic_byte(dev, SG_RATE, shortGI_rate);
2561                 //printk("==>SG_RATE:%x\n", read_nic_byte(dev, SG_RATE));
2562         }
2563         write_nic_dword(dev, ARFR0+rate_index*4, ratr_value);
2564         printk("=============>ARFR0+rate_index*4:%#x\n", ratr_value);
2565
2566         //2 UFWP
2567         if (ratr_value & 0xfffff000){
2568                 //printk("===>set to N mode\n");
2569                 HalSetFwCmd8192S(dev, FW_CMD_RA_REFRESH_N);
2570         }
2571         else    {
2572                 //printk("===>set to B/G mode\n");
2573                 HalSetFwCmd8192S(dev, FW_CMD_RA_REFRESH_BG);
2574         }
2575 }
2576
2577 void rtl8192SU_link_change(struct net_device *dev)
2578 {
2579         struct r8192_priv *priv = ieee80211_priv(dev);
2580         struct ieee80211_device* ieee = priv->ieee80211;
2581         //unsigned long flags;
2582         u32 reg = 0;
2583
2584         printk("=====>%s 1\n", __func__);
2585         reg = read_nic_dword(dev, RCR);
2586
2587         if (ieee->state == IEEE80211_LINKED)
2588         {
2589
2590                 rtl8192SU_net_update(dev);
2591                 rtl8192SU_update_ratr_table(dev);
2592                 ieee->SetFwCmdHandler(dev, FW_CMD_HIGH_PWR_ENABLE);
2593                 priv->ReceiveConfig = reg |= RCR_CBSSID;
2594
2595         }else{
2596                 priv->ReceiveConfig = reg &= ~RCR_CBSSID;
2597
2598         }
2599
2600         write_nic_dword(dev, RCR, reg);
2601         rtl8192_update_msr(dev);
2602
2603         printk("<=====%s 2\n", __func__);
2604 }
2605
2606 static struct ieee80211_qos_parameters def_qos_parameters = {
2607         {3,3,3,3},/* cw_min */
2608         {7,7,7,7},/* cw_max */
2609         {2,2,2,2},/* aifs */
2610         {0,0,0,0},/* flags */
2611         {0,0,0,0} /* tx_op_limit */
2612 };
2613
2614
2615 void rtl8192_update_beacon(struct work_struct * work)
2616 {
2617         struct r8192_priv *priv = container_of(work, struct r8192_priv, update_beacon_wq.work);
2618         struct net_device *dev = priv->ieee80211->dev;
2619         struct ieee80211_device* ieee = priv->ieee80211;
2620         struct ieee80211_network* net = &ieee->current_network;
2621
2622         if (ieee->pHTInfo->bCurrentHTSupport)
2623                 HTUpdateSelfAndPeerSetting(ieee, net);
2624         ieee->pHTInfo->bCurrentRT2RTLongSlotTime = net->bssht.bdRT2RTLongSlotTime;
2625         // Joseph test for turbo mode with AP
2626         ieee->pHTInfo->RT2RT_HT_Mode = net->bssht.RT2RT_HT_Mode;
2627         rtl8192_update_cap(dev, net->capability);
2628 }
2629 /*
2630 * background support to run QoS activate functionality
2631 */
2632 int WDCAPARA_ADD[] = {EDCAPARA_BE,EDCAPARA_BK,EDCAPARA_VI,EDCAPARA_VO};
2633
2634 void rtl8192_qos_activate(struct work_struct * work)
2635 {
2636         struct r8192_priv *priv = container_of(work, struct r8192_priv, qos_activate);
2637         struct net_device *dev = priv->ieee80211->dev;
2638         struct ieee80211_qos_parameters *qos_parameters = &priv->ieee80211->current_network.qos_data.parameters;
2639         u8 mode = priv->ieee80211->current_network.mode;
2640         //u32 size = sizeof(struct ieee80211_qos_parameters);
2641         u8  u1bAIFS;
2642         u32 u4bAcParam;
2643         int i;
2644
2645         if (priv == NULL)
2646                 return;
2647
2648        mutex_lock(&priv->mutex);
2649
2650         if(priv->ieee80211->state != IEEE80211_LINKED)
2651                 goto success;
2652         RT_TRACE(COMP_QOS,"qos active process with associate response received\n");
2653         /* It better set slot time at first */
2654         /* For we just support b/g mode at present, let the slot time at 9/20 selection */
2655         /* update the ac parameter to related registers */
2656         for(i = 0; i <  QOS_QUEUE_NUM; i++) {
2657                 //Mode G/A: slotTimeTimer = 9; Mode B: 20
2658                 u1bAIFS = qos_parameters->aifs[i] * ((mode&(IEEE_G|IEEE_N_24G)) ?9:20) + aSifsTime;
2659                 u4bAcParam = ((((u32)(qos_parameters->tx_op_limit[i]))<< AC_PARAM_TXOP_LIMIT_OFFSET)|
2660                                 (((u32)(qos_parameters->cw_max[i]))<< AC_PARAM_ECW_MAX_OFFSET)|
2661                                 (((u32)(qos_parameters->cw_min[i]))<< AC_PARAM_ECW_MIN_OFFSET)|
2662                                 ((u32)u1bAIFS << AC_PARAM_AIFS_OFFSET));
2663
2664                 write_nic_dword(dev, WDCAPARA_ADD[i], u4bAcParam);
2665                 //write_nic_dword(dev, WDCAPARA_ADD[i], 0x005e4322);
2666         }
2667
2668 success:
2669        mutex_unlock(&priv->mutex);
2670 }
2671
2672 static int rtl8192_qos_handle_probe_response(struct r8192_priv *priv,
2673                 int active_network,
2674                 struct ieee80211_network *network)
2675 {
2676         int ret = 0;
2677         u32 size = sizeof(struct ieee80211_qos_parameters);
2678
2679         if(priv->ieee80211->state !=IEEE80211_LINKED)
2680                 return ret;
2681
2682         if ((priv->ieee80211->iw_mode != IW_MODE_INFRA))
2683                 return ret;
2684
2685         if (network->flags & NETWORK_HAS_QOS_MASK) {
2686                 if (active_network &&
2687                                 (network->flags & NETWORK_HAS_QOS_PARAMETERS))
2688                         network->qos_data.active = network->qos_data.supported;
2689
2690                 if ((network->qos_data.active == 1) && (active_network == 1) &&
2691                                 (network->flags & NETWORK_HAS_QOS_PARAMETERS) &&
2692                                 (network->qos_data.old_param_count !=
2693                                  network->qos_data.param_count)) {
2694                         network->qos_data.old_param_count =
2695                                 network->qos_data.param_count;
2696                         queue_work(priv->priv_wq, &priv->qos_activate);
2697                         RT_TRACE (COMP_QOS, "QoS parameters change call "
2698                                         "qos_activate\n");
2699                 }
2700         } else {
2701                 memcpy(&priv->ieee80211->current_network.qos_data.parameters,\
2702                        &def_qos_parameters, size);
2703
2704                 if ((network->qos_data.active == 1) && (active_network == 1)) {
2705                         queue_work(priv->priv_wq, &priv->qos_activate);
2706                         RT_TRACE(COMP_QOS, "QoS was disabled call qos_activate \n");
2707                 }
2708                 network->qos_data.active = 0;
2709                 network->qos_data.supported = 0;
2710         }
2711
2712         return 0;
2713 }
2714
2715 /* handle manage frame frame beacon and probe response */
2716 static int rtl8192_handle_beacon(struct net_device * dev,
2717                                  struct ieee80211_probe_response *beacon,
2718                                  struct ieee80211_network *network)
2719 {
2720         struct r8192_priv *priv = ieee80211_priv(dev);
2721
2722         rtl8192_qos_handle_probe_response(priv,1,network);
2723         queue_delayed_work(priv->priv_wq, &priv->update_beacon_wq, 0);
2724
2725         return 0;
2726
2727 }
2728
2729 /*
2730 * handling the beaconing responses. if we get different QoS setting
2731 * off the network from the associated setting, adjust the QoS
2732 * setting
2733 */
2734 static int rtl8192_qos_association_resp(struct r8192_priv *priv,
2735                                     struct ieee80211_network *network)
2736 {
2737         int ret = 0;
2738         unsigned long flags;
2739         u32 size = sizeof(struct ieee80211_qos_parameters);
2740         int set_qos_param = 0;
2741
2742         if ((priv == NULL) || (network == NULL))
2743                 return ret;
2744
2745         if(priv->ieee80211->state !=IEEE80211_LINKED)
2746                 return ret;
2747
2748         if ((priv->ieee80211->iw_mode != IW_MODE_INFRA))
2749                 return ret;
2750
2751         spin_lock_irqsave(&priv->ieee80211->lock, flags);
2752         if(network->flags & NETWORK_HAS_QOS_PARAMETERS) {
2753                 memcpy(&priv->ieee80211->current_network.qos_data.parameters,\
2754                          &network->qos_data.parameters,\
2755                         sizeof(struct ieee80211_qos_parameters));
2756                 priv->ieee80211->current_network.qos_data.active = 1;
2757                  {
2758                         set_qos_param = 1;
2759                         /* update qos parameter for current network */
2760                         priv->ieee80211->current_network.qos_data.old_param_count = \
2761                                  priv->ieee80211->current_network.qos_data.param_count;
2762                         priv->ieee80211->current_network.qos_data.param_count = \
2763                                  network->qos_data.param_count;
2764                 }
2765         } else {
2766                 memcpy(&priv->ieee80211->current_network.qos_data.parameters,\
2767                        &def_qos_parameters, size);
2768                 priv->ieee80211->current_network.qos_data.active = 0;
2769                 priv->ieee80211->current_network.qos_data.supported = 0;
2770                 set_qos_param = 1;
2771         }
2772
2773         spin_unlock_irqrestore(&priv->ieee80211->lock, flags);
2774
2775         RT_TRACE(COMP_QOS, "%s: network->flags = %d,%d\n",__FUNCTION__,network->flags ,priv->ieee80211->current_network.qos_data.active);
2776         if (set_qos_param == 1)
2777                 queue_work(priv->priv_wq, &priv->qos_activate);
2778
2779         return ret;
2780 }
2781
2782
2783 static int rtl8192_handle_assoc_response(struct net_device *dev,
2784                                      struct ieee80211_assoc_response_frame *resp,
2785                                      struct ieee80211_network *network)
2786 {
2787         struct r8192_priv *priv = ieee80211_priv(dev);
2788         rtl8192_qos_association_resp(priv, network);
2789         return 0;
2790 }
2791
2792
2793 void rtl8192_update_ratr_table(struct net_device* dev)
2794         //      POCTET_STRING   posLegacyRate,
2795         //      u8*                     pMcsRate)
2796         //      PRT_WLAN_STA    pEntry)
2797 {
2798         struct r8192_priv* priv = ieee80211_priv(dev);
2799         struct ieee80211_device* ieee = priv->ieee80211;
2800         u8* pMcsRate = ieee->dot11HTOperationalRateSet;
2801         //struct ieee80211_network *net = &ieee->current_network;
2802         u32 ratr_value = 0;
2803         u8 rate_index = 0;
2804         rtl8192_config_rate(dev, (u16*)(&ratr_value));
2805         ratr_value |= (*(u16*)(pMcsRate)) << 12;
2806 //      switch (net->mode)
2807         switch (ieee->mode)
2808         {
2809                 case IEEE_A:
2810                         ratr_value &= 0x00000FF0;
2811                         break;
2812                 case IEEE_B:
2813                         ratr_value &= 0x0000000F;
2814                         break;
2815                 case IEEE_G:
2816                         ratr_value &= 0x00000FF7;
2817                         break;
2818                 case IEEE_N_24G:
2819                 case IEEE_N_5G:
2820                         if (ieee->pHTInfo->PeerMimoPs == 0) //MIMO_PS_STATIC
2821                                 ratr_value &= 0x0007F007;
2822                         else{
2823                                 if (priv->rf_type == RF_1T2R)
2824                                         ratr_value &= 0x000FF007;
2825                                 else
2826                                         ratr_value &= 0x0F81F007;
2827                         }
2828                         break;
2829                 default:
2830                         break;
2831         }
2832         ratr_value &= 0x0FFFFFFF;
2833         if(ieee->pHTInfo->bCurTxBW40MHz && ieee->pHTInfo->bCurShortGI40MHz){
2834                 ratr_value |= 0x80000000;
2835         }else if(!ieee->pHTInfo->bCurTxBW40MHz && ieee->pHTInfo->bCurShortGI20MHz){
2836                 ratr_value |= 0x80000000;
2837         }
2838         write_nic_dword(dev, RATR0+rate_index*4, ratr_value);
2839         write_nic_byte(dev, UFWP, 1);
2840 }
2841
2842 static u8 ccmp_ie[4] = {0x00,0x50,0xf2,0x04};
2843 static u8 ccmp_rsn_ie[4] = {0x00, 0x0f, 0xac, 0x04};
2844 bool GetNmodeSupportBySecCfg8192(struct net_device*dev)
2845 {
2846 #if 1
2847         struct r8192_priv* priv = ieee80211_priv(dev);
2848         struct ieee80211_device* ieee = priv->ieee80211;
2849         struct ieee80211_network * network = &ieee->current_network;
2850         int wpa_ie_len= ieee->wpa_ie_len;
2851         struct ieee80211_crypt_data* crypt;
2852         int encrypt;
2853         return TRUE;
2854
2855         crypt = ieee->crypt[ieee->tx_keyidx];
2856         //we use connecting AP's capability instead of only security config on our driver to distinguish whether it should use N mode or G mode
2857         encrypt = (network->capability & WLAN_CAPABILITY_PRIVACY) || (ieee->host_encrypt && crypt && crypt->ops && (0 == strcmp(crypt->ops->name,"WEP")));
2858
2859         /* simply judge  */
2860         if(encrypt && (wpa_ie_len == 0)) {
2861                 /* wep encryption, no N mode setting */
2862                 return false;
2863 //      } else if((wpa_ie_len != 0)&&(memcmp(&(ieee->wpa_ie[14]),ccmp_ie,4))) {
2864         } else if((wpa_ie_len != 0)) {
2865                 /* parse pairwise key type */
2866                 //if((pairwisekey = WEP40)||(pairwisekey = WEP104)||(pairwisekey = TKIP))
2867                 if (((ieee->wpa_ie[0] == 0xdd) && (!memcmp(&(ieee->wpa_ie[14]),ccmp_ie,4))) || ((ieee->wpa_ie[0] == 0x30) && (!memcmp(&ieee->wpa_ie[10],ccmp_rsn_ie, 4))))
2868                         return true;
2869                 else
2870                         return false;
2871         } else {
2872                 return true;
2873         }
2874
2875         return true;
2876 #endif
2877 }
2878
2879 bool GetHalfNmodeSupportByAPs819xUsb(struct net_device* dev)
2880 {
2881         bool                    Reval;
2882         struct r8192_priv* priv = ieee80211_priv(dev);
2883         struct ieee80211_device* ieee = priv->ieee80211;
2884
2885 //      Added by Roger, 2008.08.29.
2886         return false;
2887
2888         if(ieee->bHalfWirelessN24GMode == true)
2889                 Reval = true;
2890         else
2891                 Reval =  false;
2892
2893         return Reval;
2894 }
2895
2896 void rtl8192_refresh_supportrate(struct r8192_priv* priv)
2897 {
2898         struct ieee80211_device* ieee = priv->ieee80211;
2899         //we donot consider set support rate for ABG mode, only HT MCS rate is set here.
2900         if (ieee->mode == WIRELESS_MODE_N_24G || ieee->mode == WIRELESS_MODE_N_5G)
2901         {
2902                 memcpy(ieee->Regdot11HTOperationalRateSet, ieee->RegHTSuppRateSet, 16);
2903                 //RT_DEBUG_DATA(COMP_INIT, ieee->RegHTSuppRateSet, 16);
2904                 //RT_DEBUG_DATA(COMP_INIT, ieee->Regdot11HTOperationalRateSet, 16);
2905         }
2906         else
2907                 memset(ieee->Regdot11HTOperationalRateSet, 0, 16);
2908         return;
2909 }
2910
2911 u8 rtl8192_getSupportedWireleeMode(struct net_device*dev)
2912 {
2913         struct r8192_priv *priv = ieee80211_priv(dev);
2914         u8 ret = 0;
2915         switch(priv->rf_chip)
2916         {
2917                 case RF_8225:
2918                 case RF_8256:
2919                 case RF_PSEUDO_11N:
2920                 case RF_6052:
2921                         ret = (WIRELESS_MODE_N_24G|WIRELESS_MODE_G|WIRELESS_MODE_B);
2922                         break;
2923                 case RF_8258:
2924                         ret = (WIRELESS_MODE_A|WIRELESS_MODE_N_5G);
2925                         break;
2926                 default:
2927                         ret = WIRELESS_MODE_B;
2928                         break;
2929         }
2930         return ret;
2931 }
2932 void rtl8192_SetWirelessMode(struct net_device* dev, u8 wireless_mode)
2933 {
2934         struct r8192_priv *priv = ieee80211_priv(dev);
2935         u8 bSupportMode = rtl8192_getSupportedWireleeMode(dev);
2936
2937 #if 1
2938         if ((wireless_mode == WIRELESS_MODE_AUTO) || ((wireless_mode&bSupportMode)==0))
2939         {
2940                 if(bSupportMode & WIRELESS_MODE_N_24G)
2941                 {
2942                         wireless_mode = WIRELESS_MODE_N_24G;
2943                 }
2944                 else if(bSupportMode & WIRELESS_MODE_N_5G)
2945                 {
2946                         wireless_mode = WIRELESS_MODE_N_5G;
2947                 }
2948                 else if((bSupportMode & WIRELESS_MODE_A))
2949                 {
2950                         wireless_mode = WIRELESS_MODE_A;
2951                 }
2952                 else if((bSupportMode & WIRELESS_MODE_G))
2953                 {
2954                         wireless_mode = WIRELESS_MODE_G;
2955                 }
2956                 else if((bSupportMode & WIRELESS_MODE_B))
2957                 {
2958                         wireless_mode = WIRELESS_MODE_B;
2959                 }
2960                 else{
2961                         RT_TRACE(COMP_ERR, "%s(), No valid wireless mode supported, SupportedWirelessMode(%x)!!!\n", __FUNCTION__,bSupportMode);
2962                         wireless_mode = WIRELESS_MODE_B;
2963                 }
2964         }
2965 #ifdef TO_DO_LIST //// TODO: this function doesn't work well at this time, we should wait for FPGA
2966         ActUpdateChannelAccessSetting( pAdapter, pHalData->CurrentWirelessMode, &pAdapter->MgntInfo.Info8185.ChannelAccessSetting );
2967 #endif
2968         //LZM 090306 usb crash here, mark it temp
2969         //write_nic_word(dev, SIFS_OFDM, 0x0e0e);
2970         priv->ieee80211->mode = wireless_mode;
2971
2972         if ((wireless_mode == WIRELESS_MODE_N_24G) ||  (wireless_mode == WIRELESS_MODE_N_5G))
2973                 priv->ieee80211->pHTInfo->bEnableHT = 1;
2974         else
2975                 priv->ieee80211->pHTInfo->bEnableHT = 0;
2976         RT_TRACE(COMP_INIT, "Current Wireless Mode is %x\n", wireless_mode);
2977         rtl8192_refresh_supportrate(priv);
2978 #endif
2979
2980 }
2981
2982
2983 short rtl8192_is_tx_queue_empty(struct net_device *dev)
2984 {
2985         int i=0;
2986         struct r8192_priv *priv = ieee80211_priv(dev);
2987         //struct ieee80211_device* ieee = priv->ieee80211;
2988         for (i=0; i<=MGNT_QUEUE; i++)
2989         {
2990                 if ((i== TXCMD_QUEUE) || (i == HCCA_QUEUE) )
2991                         continue;
2992                 if (atomic_read(&priv->tx_pending[i]))
2993                 {
2994                         printk("===>tx queue is not empty:%d, %d\n", i, atomic_read(&priv->tx_pending[i]));
2995                         return 0;
2996                 }
2997         }
2998         return 1;
2999 }
3000
3001 void rtl8192_hw_sleep_down(struct net_device *dev)
3002 {
3003         RT_TRACE(COMP_POWER, "%s()============>come to sleep down\n", __FUNCTION__);
3004 #ifdef TODO
3005 //      MgntActSet_RF_State(dev, eRfSleep, RF_CHANGE_BY_PS);
3006 #endif
3007 }
3008
3009 void rtl8192_hw_sleep_wq (struct work_struct *work)
3010 {
3011 //      struct r8180_priv *priv = container_of(work, struct r8180_priv, watch_dog_wq);
3012 //      struct ieee80211_device * ieee = (struct ieee80211_device*)
3013 //                                             container_of(work, struct ieee80211_device, watch_dog_wq);
3014         struct delayed_work *dwork = container_of(work,struct delayed_work,work);
3015         struct ieee80211_device *ieee = container_of(dwork,struct ieee80211_device,hw_sleep_wq);
3016         struct net_device *dev = ieee->dev;
3017
3018         //printk("=========>%s()\n", __FUNCTION__);
3019         rtl8192_hw_sleep_down(dev);
3020 }
3021 //      printk("dev is %d\n",dev);
3022 //      printk("&*&(^*(&(&=========>%s()\n", __FUNCTION__);
3023 void rtl8192_hw_wakeup(struct net_device* dev)
3024 {
3025 //      u32 flags = 0;
3026
3027 //      spin_lock_irqsave(&priv->ps_lock,flags);
3028         RT_TRACE(COMP_POWER, "%s()============>come to wake up\n", __FUNCTION__);
3029 #ifdef TODO
3030 //      MgntActSet_RF_State(dev, eRfSleep, RF_CHANGE_BY_PS);
3031 #endif
3032         //FIXME: will we send package stored while nic is sleep?
3033 //      spin_unlock_irqrestore(&priv->ps_lock,flags);
3034 }
3035
3036 void rtl8192_hw_wakeup_wq (struct work_struct *work)
3037 {
3038 //      struct r8180_priv *priv = container_of(work, struct r8180_priv, watch_dog_wq);
3039 //      struct ieee80211_device * ieee = (struct ieee80211_device*)
3040 //                                             container_of(work, struct ieee80211_device, watch_dog_wq);
3041         struct delayed_work *dwork = container_of(work,struct delayed_work,work);
3042         struct ieee80211_device *ieee = container_of(dwork,struct ieee80211_device,hw_wakeup_wq);
3043         struct net_device *dev = ieee->dev;
3044
3045         rtl8192_hw_wakeup(dev);
3046 }
3047
3048 #define MIN_SLEEP_TIME 50
3049 #define MAX_SLEEP_TIME 10000
3050 void rtl8192_hw_to_sleep(struct net_device *dev, u32 th, u32 tl)
3051 {
3052
3053         struct r8192_priv *priv = ieee80211_priv(dev);
3054
3055         u32 rb = jiffies;
3056         unsigned long flags;
3057
3058         spin_lock_irqsave(&priv->ps_lock,flags);
3059
3060         /* Writing HW register with 0 equals to disable
3061          * the timer, that is not really what we want
3062          */
3063         tl -= MSECS(4+16+7);
3064
3065         //if(tl == 0) tl = 1;
3066
3067         /* FIXME HACK FIXME HACK */
3068 //      force_pci_posting(dev);
3069         //mdelay(1);
3070
3071 //      rb = read_nic_dword(dev, TSFTR);
3072
3073         /* If the interval in witch we are requested to sleep is too
3074          * short then give up and remain awake
3075          */
3076         if(((tl>=rb)&& (tl-rb) <= MSECS(MIN_SLEEP_TIME))
3077                 ||((rb>tl)&& (rb-tl) < MSECS(MIN_SLEEP_TIME))) {
3078                 spin_unlock_irqrestore(&priv->ps_lock,flags);
3079                 printk("too short to sleep\n");
3080                 return;
3081         }
3082
3083 //      write_nic_dword(dev, TimerInt, tl);
3084 //      rb = read_nic_dword(dev, TSFTR);
3085         {
3086                 u32 tmp = (tl>rb)?(tl-rb):(rb-tl);
3087         //      if (tl<rb)
3088
3089                 queue_delayed_work(priv->ieee80211->wq, &priv->ieee80211->hw_wakeup_wq, tmp); //as tl may be less than rb
3090         }
3091         /* if we suspect the TimerInt is gone beyond tl
3092          * while setting it, then give up
3093          */
3094 #if 1
3095         if(((tl > rb) && ((tl-rb) > MSECS(MAX_SLEEP_TIME)))||
3096                 ((tl < rb) && ((rb-tl) > MSECS(MAX_SLEEP_TIME)))) {
3097                 printk("========>too long to sleep:%x, %x, %lx\n", tl, rb,  MSECS(MAX_SLEEP_TIME));
3098                 spin_unlock_irqrestore(&priv->ps_lock,flags);
3099                 return;
3100         }
3101 #endif
3102 //      if(priv->rf_sleep)
3103 //              priv->rf_sleep(dev);
3104
3105         //printk("<=========%s()\n", __FUNCTION__);
3106         queue_delayed_work(priv->ieee80211->wq, (void *)&priv->ieee80211->hw_sleep_wq,0);
3107
3108         spin_unlock_irqrestore(&priv->ps_lock,flags);
3109 }
3110 //init priv variables here. only non_zero value should be initialized here.
3111 static void rtl8192_init_priv_variable(struct net_device* dev)
3112 {
3113         struct r8192_priv *priv = ieee80211_priv(dev);
3114         u8 i;
3115         priv->card_8192 = NIC_8192U;
3116         priv->chan = 1; //set to channel 1
3117         priv->ieee80211->mode = WIRELESS_MODE_AUTO; //SET AUTO
3118         priv->ieee80211->iw_mode = IW_MODE_INFRA;
3119         priv->ieee80211->ieee_up=0;
3120         priv->retry_rts = DEFAULT_RETRY_RTS;
3121         priv->retry_data = DEFAULT_RETRY_DATA;
3122         priv->ieee80211->rts = DEFAULT_RTS_THRESHOLD;
3123         priv->ieee80211->rate = 110; //11 mbps
3124         priv->ieee80211->short_slot = 1;
3125         priv->promisc = (dev->flags & IFF_PROMISC) ? 1:0;
3126         priv->CckPwEnl = 6;
3127         //for silent reset
3128         priv->IrpPendingCount = 1;
3129         priv->ResetProgress = RESET_TYPE_NORESET;
3130         priv->bForcedSilentReset = 0;
3131         priv->bDisableNormalResetCheck = false;
3132         priv->force_reset = false;
3133
3134         priv->ieee80211->FwRWRF = 0;    //we don't use FW read/write RF until stable firmware is available.
3135         priv->ieee80211->current_network.beacon_interval = DEFAULT_BEACONINTERVAL;
3136         priv->ieee80211->iw_mode = IW_MODE_INFRA;
3137         priv->ieee80211->softmac_features  = IEEE_SOFTMAC_SCAN |
3138                 IEEE_SOFTMAC_ASSOCIATE | IEEE_SOFTMAC_PROBERQ |
3139                 IEEE_SOFTMAC_PROBERS | IEEE_SOFTMAC_TX_QUEUE |
3140                 IEEE_SOFTMAC_BEACONS;//added by amy 080604 //|  //IEEE_SOFTMAC_SINGLE_QUEUE;
3141
3142         priv->ieee80211->active_scan = 1;
3143         priv->ieee80211->modulation = IEEE80211_CCK_MODULATION | IEEE80211_OFDM_MODULATION;
3144         priv->ieee80211->host_encrypt = 1;
3145         priv->ieee80211->host_decrypt = 1;
3146         priv->ieee80211->start_send_beacons = NULL;//rtl819xusb_beacon_tx;//-by amy 080604
3147         priv->ieee80211->stop_send_beacons = NULL;//rtl8192_beacon_stop;//-by amy 080604
3148         priv->ieee80211->softmac_hard_start_xmit = rtl8192_hard_start_xmit;
3149         priv->ieee80211->set_chan = rtl8192_set_chan;
3150         priv->ieee80211->link_change = priv->ops->rtl819x_link_change;
3151         priv->ieee80211->softmac_data_hard_start_xmit = rtl8192_hard_data_xmit;
3152         priv->ieee80211->data_hard_stop = rtl8192_data_hard_stop;
3153         priv->ieee80211->data_hard_resume = rtl8192_data_hard_resume;
3154         priv->ieee80211->init_wmmparam_flag = 0;
3155         priv->ieee80211->fts = DEFAULT_FRAG_THRESHOLD;
3156         priv->ieee80211->check_nic_enough_desc = check_nic_enough_desc;
3157         priv->ieee80211->tx_headroom = TX_PACKET_SHIFT_BYTES;
3158         priv->ieee80211->qos_support = 1;
3159
3160         //added by WB
3161 //      priv->ieee80211->SwChnlByTimerHandler = rtl8192_phy_SwChnl;
3162         priv->ieee80211->SetBWModeHandler = rtl8192_SetBWMode;
3163         priv->ieee80211->handle_assoc_response = rtl8192_handle_assoc_response;
3164         priv->ieee80211->handle_beacon = rtl8192_handle_beacon;
3165         //for LPS
3166         priv->ieee80211->sta_wake_up = rtl8192_hw_wakeup;
3167 //      priv->ieee80211->ps_request_tx_ack = rtl8192_rq_tx_ack;
3168         priv->ieee80211->enter_sleep_state = rtl8192_hw_to_sleep;
3169         priv->ieee80211->ps_is_queue_empty = rtl8192_is_tx_queue_empty;
3170         //added by david
3171         priv->ieee80211->GetNmodeSupportBySecCfg = GetNmodeSupportBySecCfg8192;
3172         priv->ieee80211->GetHalfNmodeSupportByAPsHandler = GetHalfNmodeSupportByAPs819xUsb;
3173         priv->ieee80211->SetWirelessMode = rtl8192_SetWirelessMode;
3174         //added by amy
3175         priv->ieee80211->InitialGainHandler = priv->ops->rtl819x_initial_gain;
3176         priv->card_type = USB;
3177
3178 //1 RTL8192SU/
3179         priv->ieee80211->current_network.beacon_interval = DEFAULT_BEACONINTERVAL;
3180         priv->ieee80211->SetFwCmdHandler = HalSetFwCmd8192S;
3181         priv->bRFSiOrPi = 0;//o=si,1=pi;
3182         //lzm add
3183         priv->bInHctTest = false;
3184
3185         priv->MidHighPwrTHR_L1 = 0x3B;
3186         priv->MidHighPwrTHR_L2 = 0x40;
3187
3188         if(priv->bInHctTest)
3189         {
3190                 priv->ShortRetryLimit = HAL_RETRY_LIMIT_AP_ADHOC;
3191                 priv->LongRetryLimit = HAL_RETRY_LIMIT_AP_ADHOC;
3192         }
3193         else
3194         {
3195                 priv->ShortRetryLimit = HAL_RETRY_LIMIT_INFRA;
3196                 priv->LongRetryLimit = HAL_RETRY_LIMIT_INFRA;
3197         }
3198
3199         priv->SetFwCmdInProgress = false; //is set FW CMD in Progress? 92S only
3200         priv->CurrentFwCmdIO = 0;
3201
3202         priv->MinSpaceCfg = 0;
3203
3204         priv->EarlyRxThreshold = 7;
3205         priv->enable_gpio0 = 0;
3206         priv->TransmitConfig    =
3207                                 ((u32)TCR_MXDMA_2048<<TCR_MXDMA_OFFSET) |       // Max DMA Burst Size per Tx DMA Burst, 7: reservied.
3208                                 (priv->ShortRetryLimit<<TCR_SRL_OFFSET) |       // Short retry limit
3209                                 (priv->LongRetryLimit<<TCR_LRL_OFFSET) |        // Long retry limit
3210                                 (false ? TCR_SAT : 0);  // FALSE: HW provies PLCP length and LENGEXT, TURE: SW proiveds them
3211         if(priv->bInHctTest)
3212                 priv->ReceiveConfig     =       //priv->CSMethod |
3213                                                                 RCR_AMF | RCR_ADF |     //RCR_AAP |     //accept management/data
3214                                                                         RCR_ACF |RCR_APPFCS|                                            //accept control frame for SW AP needs PS-poll, 2005.07.07, by rcnjko.
3215                                                                 RCR_AB | RCR_AM | RCR_APM |             //accept BC/MC/UC
3216                                                                 RCR_AICV | RCR_ACRC32 |                 //accept ICV/CRC error packet
3217                                                                 RCR_APP_PHYST_STAFF | RCR_APP_PHYST_RXFF |      // Accept PHY status
3218                                                                 ((u32)7<<RCR_MXDMA_OFFSET) | // Max DMA Burst Size per Rx DMA Burst, 7: unlimited.
3219                                                                 (priv->EarlyRxThreshold<<RCR_FIFO_OFFSET) | // Rx FIFO Threshold, 7: No Rx threshold.
3220                                                                 (priv->EarlyRxThreshold == 7 ? RCR_OnlyErlPkt:0);
3221         else
3222                 priv->ReceiveConfig     =       //priv->CSMethod |
3223                                                                         RCR_AMF | RCR_ADF | RCR_AB |
3224                                                                         RCR_AM | RCR_APM |RCR_AAP |RCR_ADD3|RCR_APP_ICV|
3225                                                                 RCR_APP_PHYST_STAFF | RCR_APP_PHYST_RXFF |      // Accept PHY status
3226                                                                         RCR_APP_MIC | RCR_APPFCS;
3227
3228         // <Roger_EXP> 2008.06.16.
3229         priv->IntrMask          =       (u16)(IMR_ROK | IMR_VODOK | IMR_VIDOK | IMR_BEDOK | IMR_BKDOK |         \
3230                                                                 IMR_HCCADOK | IMR_MGNTDOK | IMR_COMDOK | IMR_HIGHDOK |                                  \
3231                                                                 IMR_BDOK | IMR_RXCMDOK | /*IMR_TIMEOUT0 |*/ IMR_RDU | IMR_RXFOVW        |                       \
3232                                                                 IMR_TXFOVW | IMR_BcnInt | IMR_TBDOK | IMR_TBDER);
3233
3234 //1 End
3235
3236
3237         priv->AcmControl = 0;
3238         priv->pFirmware = (rt_firmware*)vmalloc(sizeof(rt_firmware));
3239         if (priv->pFirmware)
3240         memset(priv->pFirmware, 0, sizeof(rt_firmware));
3241
3242         /* rx related queue */
3243         skb_queue_head_init(&priv->rx_queue);
3244         skb_queue_head_init(&priv->skb_queue);
3245
3246         /* Tx related queue */
3247         for(i = 0; i < MAX_QUEUE_SIZE; i++) {
3248                 skb_queue_head_init(&priv->ieee80211->skb_waitQ [i]);
3249         }
3250         for(i = 0; i < MAX_QUEUE_SIZE; i++) {
3251                 skb_queue_head_init(&priv->ieee80211->skb_aggQ [i]);
3252         }
3253         for(i = 0; i < MAX_QUEUE_SIZE; i++) {
3254                 skb_queue_head_init(&priv->ieee80211->skb_drv_aggQ [i]);
3255         }
3256         priv->rf_set_chan = rtl8192_phy_SwChnl;
3257 }
3258
3259 //init lock here
3260 static void rtl8192_init_priv_lock(struct r8192_priv* priv)
3261 {
3262         spin_lock_init(&priv->tx_lock);
3263         spin_lock_init(&priv->irq_lock);//added by thomas
3264         //spin_lock_init(&priv->rf_lock);//use rf_sem, or will crash in some OS.
3265         sema_init(&priv->wx_sem,1);
3266         sema_init(&priv->rf_sem,1);
3267         spin_lock_init(&priv->ps_lock);
3268         mutex_init(&priv->mutex);
3269 }
3270
3271 extern  void    rtl819x_watchdog_wqcallback(struct work_struct *work);
3272
3273 void rtl8192_irq_rx_tasklet(struct r8192_priv *priv);
3274 //init tasklet and wait_queue here. only 2.6 above kernel is considered
3275 #define DRV_NAME "wlan0"
3276 static void rtl8192_init_priv_task(struct net_device* dev)
3277 {
3278         struct r8192_priv *priv = ieee80211_priv(dev);
3279
3280 #ifdef PF_SYNCTHREAD
3281         priv->priv_wq = create_workqueue(DRV_NAME,0);
3282 #else
3283         priv->priv_wq = create_workqueue(DRV_NAME);
3284 #endif
3285
3286         INIT_WORK(&priv->reset_wq, rtl8192_restart);
3287
3288         //INIT_DELAYED_WORK(&priv->watch_dog_wq, hal_dm_watchdog);
3289         INIT_DELAYED_WORK(&priv->watch_dog_wq, rtl819x_watchdog_wqcallback);
3290         INIT_DELAYED_WORK(&priv->txpower_tracking_wq,  dm_txpower_trackingcallback);
3291 //      INIT_DELAYED_WORK(&priv->gpio_change_rf_wq,  dm_gpio_change_rf_callback);
3292         INIT_DELAYED_WORK(&priv->rfpath_check_wq,  dm_rf_pathcheck_workitemcallback);
3293         INIT_DELAYED_WORK(&priv->update_beacon_wq, rtl8192_update_beacon);
3294         INIT_DELAYED_WORK(&priv->initialgain_operate_wq, InitialGainOperateWorkItemCallBack);
3295         //INIT_WORK(&priv->SwChnlWorkItem,  rtl8192_SwChnl_WorkItem);
3296         //INIT_WORK(&priv->SetBWModeWorkItem,  rtl8192_SetBWModeWorkItem);
3297         INIT_WORK(&priv->qos_activate, rtl8192_qos_activate);
3298         INIT_DELAYED_WORK(&priv->ieee80211->hw_wakeup_wq,(void*) rtl8192_hw_wakeup_wq);
3299         INIT_DELAYED_WORK(&priv->ieee80211->hw_sleep_wq,(void*) rtl8192_hw_sleep_wq);
3300
3301         tasklet_init(&priv->irq_rx_tasklet,
3302              (void(*)(unsigned long))rtl8192_irq_rx_tasklet,
3303              (unsigned long)priv);
3304 }
3305
3306 static void rtl8192_get_eeprom_size(struct net_device* dev)
3307 {
3308         u16 curCR = 0;
3309         struct r8192_priv *priv = ieee80211_priv(dev);
3310         RT_TRACE(COMP_EPROM, "===========>%s()\n", __FUNCTION__);
3311         curCR = read_nic_word_E(dev,EPROM_CMD);
3312         RT_TRACE(COMP_EPROM, "read from Reg EPROM_CMD(%x):%x\n", EPROM_CMD, curCR);
3313         //whether need I consider BIT5?
3314         priv->epromtype = (curCR & Cmd9346CR_9356SEL) ? EPROM_93c56 : EPROM_93c46;
3315         RT_TRACE(COMP_EPROM, "<===========%s(), epromtype:%d\n", __FUNCTION__, priv->epromtype);
3316 }
3317
3318 //used to swap endian. as ntohl & htonl are not neccessary to swap endian, so use this instead.
3319 static inline u16 endian_swap(u16* data)
3320 {
3321         u16 tmp = *data;
3322         *data = (tmp >> 8) | (tmp << 8);
3323         return *data;
3324 }
3325
3326 u8 rtl8192SU_UsbOptionToEndPointNumber(u8 UsbOption)
3327 {
3328         u8      nEndPoint = 0;
3329         switch(UsbOption)
3330         {
3331                 case 0:
3332                         nEndPoint = 6;
3333                         break;
3334                 case 1:
3335                         nEndPoint = 11;
3336                         break;
3337                 case 2:
3338                         nEndPoint = 4;
3339                         break;
3340                 default:
3341                         RT_TRACE(COMP_INIT, "UsbOptionToEndPointNumber(): Invalid UsbOption(%#x)\n", UsbOption);
3342                         break;
3343         }
3344         return nEndPoint;
3345 }
3346
3347 u8 rtl8192SU_BoardTypeToRFtype(struct net_device* dev,  u8 Boardtype)
3348 {
3349         u8      RFtype = RF_1T2R;
3350
3351         switch(Boardtype)
3352         {
3353                 case 0:
3354                         RFtype = RF_1T1R;
3355                         break;
3356                 case 1:
3357                         RFtype = RF_1T2R;
3358                         break;
3359                 case 2:
3360                         RFtype = RF_2T2R;
3361                         break;
3362                 case 3:
3363                         RFtype = RF_2T2R_GREEN;
3364                         break;
3365                 default:
3366                         break;
3367         }
3368
3369         return RFtype;
3370 }
3371
3372 void update_hal_variables(struct r8192_priv *priv)
3373 {
3374         int rf_path;
3375         int i;
3376         u8 index;
3377
3378         for (rf_path = 0; rf_path < 2; rf_path++) {
3379                 for (i = 0; i < 3; i++) {
3380                         RT_TRACE((COMP_INIT), "CCK RF-%d CHan_Area-%d = 0x%x\n", rf_path, i, priv->RfCckChnlAreaTxPwr[rf_path][i]);
3381                         RT_TRACE((COMP_INIT), "OFDM-1T RF-%d CHan_Area-%d = 0x%x\n", rf_path, i, priv->RfOfdmChnlAreaTxPwr1T[rf_path][i]);
3382                         RT_TRACE((COMP_INIT), "OFDM-2T RF-%d CHan_Area-%d = 0x%x\n", rf_path, i, priv->RfOfdmChnlAreaTxPwr2T[rf_path][i]);
3383                 }
3384                 /* Assign dedicated channel tx power */
3385                 for(i = 0; i < 14; i++) {
3386                         /* channel 1-3 use the same Tx Power Level. */
3387                         if (i < 3)                      /* Channel 1-3 */
3388                                 index = 0;
3389                         else if (i < 9)                 /* Channel 4-9 */
3390                                 index = 1;
3391                         else                            /* Channel 10-14 */
3392                                 index = 2;
3393                         /* Record A & B CCK /OFDM - 1T/2T Channel area tx power */
3394                         priv->RfTxPwrLevelCck[rf_path][i] = priv->RfCckChnlAreaTxPwr[rf_path][index];
3395                         priv->RfTxPwrLevelOfdm1T[rf_path][i]  = priv->RfOfdmChnlAreaTxPwr1T[rf_path][index];
3396                         priv->RfTxPwrLevelOfdm2T[rf_path][i]  = priv->RfOfdmChnlAreaTxPwr2T[rf_path][index];
3397                         if (rf_path == 0) {
3398                                 priv->TxPowerLevelOFDM24G[i] = priv->RfTxPwrLevelOfdm1T[rf_path][i] ;
3399                                 priv->TxPowerLevelCCK[i] = priv->RfTxPwrLevelCck[rf_path][i];
3400                         }
3401                 }
3402                 for(i = 0; i < 14; i++) {
3403                         RT_TRACE((COMP_INIT),
3404                         "Rf-%d TxPwr CH-%d CCK OFDM_1T OFDM_2T= 0x%x/0x%x/0x%x\n",
3405                                 rf_path, i, priv->RfTxPwrLevelCck[rf_path][i],
3406                                 priv->RfTxPwrLevelOfdm1T[rf_path][i] ,
3407                                 priv->RfTxPwrLevelOfdm2T[rf_path][i] );
3408                 }
3409         }
3410 }
3411
3412 //
3413 //      Description:
3414 //              Config HW adapter information into initial value.
3415 //
3416 //      Assumption:
3417 //              1. After Auto load fail(i.e, check CR9346 fail)
3418 //
3419 //      Created by Roger, 2008.10.21.
3420 //
3421 void
3422 rtl8192SU_ConfigAdapterInfo8192SForAutoLoadFail(struct net_device* dev)
3423 {
3424         struct r8192_priv       *priv = ieee80211_priv(dev);
3425         //u16                   i,usValue;
3426         //u8 sMacAddr[6] = {0x00, 0xE0, 0x4C, 0x81, 0x92, 0x00};
3427         u8              rf_path;        // For EEPROM/EFUSE After V0.6_1117
3428         int     i;
3429
3430         RT_TRACE(COMP_INIT, "====> ConfigAdapterInfo8192SForAutoLoadFail\n");
3431
3432         write_nic_byte(dev, SYS_ISO_CTRL+1, 0xE8); // Isolation signals from Loader
3433         //PlatformStallExecution(10000);
3434         mdelay(10);
3435         write_nic_byte(dev, PMC_FSM, 0x02); // Enable Loader Data Keep
3436
3437         //RT_ASSERT(priv->AutoloadFailFlag==TRUE, ("ReadAdapterInfo8192SEEPROM(): AutoloadFailFlag !=TRUE\n"));
3438
3439         // Initialize IC Version && Channel Plan
3440         priv->eeprom_vid = 0;
3441         priv->eeprom_pid = 0;
3442         priv->card_8192_version = 0;
3443         priv->eeprom_ChannelPlan = 0;
3444         priv->eeprom_CustomerID = 0;
3445         priv->eeprom_SubCustomerID = 0;
3446         priv->bIgnoreDiffRateTxPowerOffset = false;
3447
3448         RT_TRACE(COMP_INIT, "EEPROM VID = 0x%4x\n", priv->eeprom_vid);
3449         RT_TRACE(COMP_INIT, "EEPROM PID = 0x%4x\n", priv->eeprom_pid);
3450         RT_TRACE(COMP_INIT, "EEPROM Customer ID: 0x%2x\n", priv->eeprom_CustomerID);
3451         RT_TRACE(COMP_INIT, "EEPROM SubCustomer ID: 0x%2x\n", priv->eeprom_SubCustomerID);
3452         RT_TRACE(COMP_INIT, "EEPROM ChannelPlan = 0x%4x\n", priv->eeprom_ChannelPlan);
3453         RT_TRACE(COMP_INIT, "IgnoreDiffRateTxPowerOffset = %d\n", priv->bIgnoreDiffRateTxPowerOffset);
3454
3455
3456
3457         priv->EEPROMUsbOption = EEPROM_USB_Default_OPTIONAL_FUNC;
3458         RT_TRACE(COMP_INIT, "USB Option = %#x\n", priv->EEPROMUsbOption);
3459
3460         for(i=0; i<5; i++)
3461                 priv->EEPROMUsbPhyParam[i] = EEPROM_USB_Default_PHY_PARAM;
3462
3463         //RT_PRINT_DATA(COMP_INIT|COMP_EFUSE, DBG_LOUD, ("EFUSE USB PHY Param: \n"), priv->EEPROMUsbPhyParam, 5);
3464
3465         {
3466         //<Roger_Notes> In this case, we random assigh MAC address here. 2008.10.15.
3467                 static u8 sMacAddr[6] = {0x00, 0xE0, 0x4C, 0x81, 0x92, 0x00};
3468                 u8      i;
3469
3470                 //sMacAddr[5] = (u8)GetRandomNumber(1, 254);
3471
3472                 for(i = 0; i < 6; i++)
3473                         dev->dev_addr[i] = sMacAddr[i];
3474         }
3475         //NicIFSetMacAddress(Adapter, Adapter->PermanentAddress);
3476         write_nic_dword(dev, IDR0, ((u32*)dev->dev_addr)[0]);
3477         write_nic_word(dev, IDR4, ((u16*)(dev->dev_addr + 4))[0]);
3478
3479         RT_TRACE(COMP_INIT,
3480                 "ReadAdapterInfo8192SEFuse(), Permanent Address = %pM\n",
3481                 dev->dev_addr);
3482
3483         priv->EEPROMBoardType = EEPROM_Default_BoardType;
3484         priv->rf_type = RF_1T2R; //RF_2T2R
3485         priv->EEPROMTxPowerDiff = EEPROM_Default_PwDiff;
3486         priv->EEPROMThermalMeter = EEPROM_Default_ThermalMeter;
3487         priv->EEPROMCrystalCap = EEPROM_Default_CrystalCap;
3488         priv->EEPROMTxPwrBase = EEPROM_Default_TxPowerBase;
3489         priv->EEPROMTSSI_A = EEPROM_Default_TSSI;
3490         priv->EEPROMTSSI_B = EEPROM_Default_TSSI;
3491         priv->EEPROMTxPwrTkMode = EEPROM_Default_TxPwrTkMode;
3492
3493
3494
3495         for (rf_path = 0; rf_path < 2; rf_path++)
3496         {
3497                 for (i = 0; i < 3; i++)
3498                 {
3499                         // Read CCK RF A & B Tx power
3500                         priv->RfCckChnlAreaTxPwr[rf_path][i] =
3501                         priv->RfOfdmChnlAreaTxPwr1T[rf_path][i] =
3502                         priv->RfOfdmChnlAreaTxPwr2T[rf_path][i] =
3503                         (u8)(EEPROM_Default_TxPower & 0xff);
3504                 }
3505         }
3506
3507         update_hal_variables(priv);
3508
3509         //
3510         // Update remained HAL variables.
3511         //
3512         priv->TSSI_13dBm = priv->EEPROMThermalMeter *100;
3513         priv->LegacyHTTxPowerDiff = priv->EEPROMTxPowerDiff;//new
3514         priv->TxPowerDiff = priv->EEPROMTxPowerDiff;
3515         //priv->AntennaTxPwDiff[0] = (priv->EEPROMTxPowerDiff & 0xf);// Antenna B gain offset to antenna A, bit0~3
3516         //priv->AntennaTxPwDiff[1] = ((priv->EEPROMTxPowerDiff & 0xf0)>>4);// Antenna C gain offset to antenna A, bit4~7
3517         priv->CrystalCap = priv->EEPROMCrystalCap;      // CrystalCap, bit12~15
3518         priv->ThermalMeter[0] = priv->EEPROMThermalMeter;// ThermalMeter, bit0~3 for RFIC1, bit4~7 for RFIC2
3519         priv->LedStrategy = SW_LED_MODE0;
3520
3521         init_rate_adaptive(dev);
3522
3523         RT_TRACE(COMP_INIT, "<==== ConfigAdapterInfo8192SForAutoLoadFail\n");
3524
3525 }
3526
3527 //
3528 //      Description:
3529 //              Read HW adapter information by E-Fuse or EEPROM according CR9346 reported.
3530 //
3531 //      Assumption:
3532 //              1. CR9346 regiser has verified.
3533 //              2. PASSIVE_LEVEL (USB interface)
3534 //
3535 //      Created by Roger, 2008.10.21.
3536 //
3537 void
3538 rtl8192SU_ReadAdapterInfo8192SUsb(struct net_device* dev)
3539 {
3540         struct r8192_priv       *priv = ieee80211_priv(dev);
3541         u16                     i,usValue;
3542         u8                      tmpU1b, tempval;
3543         u16                     EEPROMId;
3544         u8                      hwinfo[HWSET_MAX_SIZE_92S];
3545         u8                      rf_path, index; // For EEPROM/EFUSE After V0.6_1117
3546
3547
3548         RT_TRACE(COMP_INIT, "====> ReadAdapterInfo8192SUsb\n");
3549
3550         //
3551         // <Roger_Note> The following operation are prevent Efuse leakage by turn on 2.5V.
3552         // 2008.11.25.
3553         //
3554         tmpU1b = read_nic_byte(dev, EFUSE_TEST+3);
3555         write_nic_byte(dev, EFUSE_TEST+3, tmpU1b|0x80);
3556         //PlatformStallExecution(1000);
3557         mdelay(10);
3558         write_nic_byte(dev, EFUSE_TEST+3, (tmpU1b&(~BIT7)));
3559
3560         // Retrieve Chip version.
3561         priv->card_8192_version = (VERSION_8192S)((read_nic_dword(dev, PMC_FSM)>>16)&0xF);
3562         RT_TRACE(COMP_INIT, "Chip Version ID: 0x%2x\n", priv->card_8192_version);
3563
3564         switch(priv->card_8192_version)
3565         {
3566                 case 0:
3567                         RT_TRACE(COMP_INIT, "Chip Version ID: VERSION_8192S_ACUT.\n");
3568                         break;
3569                 case 1:
3570                         RT_TRACE(COMP_INIT, "Chip Version ID: VERSION_8192S_BCUT.\n");
3571                         break;
3572                 case 2:
3573                         RT_TRACE(COMP_INIT, "Chip Version ID: VERSION_8192S_CCUT.\n");
3574                         break;
3575                 default:
3576                         RT_TRACE(COMP_INIT, "Unknown Chip Version!!\n");
3577                         priv->card_8192_version = VERSION_8192S_BCUT;
3578                         break;
3579         }
3580
3581         //if (IS_BOOT_FROM_EEPROM(Adapter))
3582         if(priv->EepromOrEfuse)
3583         {       // Read frin EEPROM
3584                 write_nic_byte(dev, SYS_ISO_CTRL+1, 0xE8); // Isolation signals from Loader
3585                 //PlatformStallExecution(10000);
3586                 mdelay(10);
3587                 write_nic_byte(dev, PMC_FSM, 0x02); // Enable Loader Data Keep
3588                 // Read all Content from EEPROM or EFUSE.
3589                 for(i = 0; i < HWSET_MAX_SIZE_92S; i += 2)
3590                 {
3591                         usValue = eprom_read(dev, (u16) (i>>1));
3592                         *((u16*)(&hwinfo[i])) = usValue;
3593                 }
3594         }
3595         else if (!(priv->EepromOrEfuse))
3596         {       // Read from EFUSE
3597
3598                 //
3599                 // <Roger_Notes> We set Isolation signals from Loader and reset EEPROM after system resuming
3600                 // from suspend mode.
3601                 // 2008.10.21.
3602                 //
3603                 //PlatformEFIOWrite1Byte(Adapter, SYS_ISO_CTRL+1, 0xE8); // Isolation signals from Loader
3604                 //PlatformStallExecution(10000);
3605                 //PlatformEFIOWrite1Byte(Adapter, SYS_FUNC_EN+1, 0x40);
3606                 //PlatformEFIOWrite1Byte(Adapter, SYS_FUNC_EN+1, 0x50);
3607
3608                 //tmpU1b = PlatformEFIORead1Byte(Adapter, EFUSE_TEST+3);
3609                 //PlatformEFIOWrite1Byte(Adapter, EFUSE_TEST+3, (tmpU1b | 0x80));
3610                 //PlatformEFIOWrite1Byte(Adapter, EFUSE_TEST+3, 0x72);
3611                 //PlatformEFIOWrite1Byte(Adapter, EFUSE_CLK, 0x03);
3612
3613                 // Read EFUSE real map to shadow.
3614                 EFUSE_ShadowMapUpdate(dev);
3615                 memcpy(hwinfo, &priv->EfuseMap[EFUSE_INIT_MAP][0], HWSET_MAX_SIZE_92S);
3616         }
3617         else
3618         {
3619                 RT_TRACE(COMP_INIT, "ReadAdapterInfo8192SUsb(): Invalid boot type!!\n");
3620         }
3621
3622         //YJ,test,090106
3623         //dump_buf(hwinfo,HWSET_MAX_SIZE_92S);
3624         //
3625         // <Roger_Notes> The following are EFUSE/EEPROM independent operations!!
3626         //
3627         //RT_PRINT_DATA(COMP_EFUSE, DBG_LOUD, ("MAP: \n"), hwinfo, HWSET_MAX_SIZE_92S);
3628
3629         //
3630         // <Roger_Notes> Event though CR9346 regiser can verify whether Autoload is success or not, but we still
3631         // double check ID codes for 92S here(e.g., due to HW GPIO polling fail issue).
3632         // 2008.10.21.
3633         //
3634         EEPROMId = *((u16 *)&hwinfo[0]);
3635
3636         if( EEPROMId != RTL8190_EEPROM_ID )
3637         {
3638                 RT_TRACE(COMP_INIT, "ID(%#x) is invalid!!\n", EEPROMId);
3639                 priv->bTXPowerDataReadFromEEPORM = FALSE;
3640                 priv->AutoloadFailFlag=TRUE;
3641         }
3642         else
3643         {
3644                 priv->AutoloadFailFlag=FALSE;
3645                 priv->bTXPowerDataReadFromEEPORM = TRUE;
3646         }
3647        // Read IC Version && Channel Plan
3648         if(!priv->AutoloadFailFlag)
3649         {
3650                 // VID, PID
3651                 priv->eeprom_vid = *(u16 *)&hwinfo[EEPROM_VID];
3652                 priv->eeprom_pid = *(u16 *)&hwinfo[EEPROM_PID];
3653                 priv->bIgnoreDiffRateTxPowerOffset = false;     //cosa for test
3654
3655
3656                 // EEPROM Version ID, Channel plan
3657                 priv->EEPROMVersion = *(u8 *)&hwinfo[EEPROM_Version];
3658                 priv->eeprom_ChannelPlan = *(u8 *)&hwinfo[EEPROM_ChannelPlan];
3659
3660                 // Customer ID, 0x00 and 0xff are reserved for Realtek.
3661                 priv->eeprom_CustomerID = *(u8 *)&hwinfo[EEPROM_CustomID];
3662                 priv->eeprom_SubCustomerID = *(u8 *)&hwinfo[EEPROM_SubCustomID];
3663         }
3664         else
3665         {
3666                 //priv->eeprom_vid = 0;
3667                 //priv->eeprom_pid = 0;
3668                 //priv->EEPROMVersion = 0;
3669                 //priv->eeprom_ChannelPlan = 0;
3670                 //priv->eeprom_CustomerID = 0;
3671                 //priv->eeprom_SubCustomerID = 0;
3672
3673                 rtl8192SU_ConfigAdapterInfo8192SForAutoLoadFail(dev);
3674                 return;
3675         }
3676
3677
3678         RT_TRACE(COMP_INIT, "EEPROM Id = 0x%4x\n", EEPROMId);
3679         RT_TRACE(COMP_INIT, "EEPROM VID = 0x%4x\n", priv->eeprom_vid);
3680         RT_TRACE(COMP_INIT, "EEPROM PID = 0x%4x\n", priv->eeprom_pid);
3681         RT_TRACE(COMP_INIT, "EEPROM Version ID: 0x%2x\n", priv->EEPROMVersion);
3682         RT_TRACE(COMP_INIT, "EEPROM Customer ID: 0x%2x\n", priv->eeprom_CustomerID);
3683         RT_TRACE(COMP_INIT, "EEPROM SubCustomer ID: 0x%2x\n", priv->eeprom_SubCustomerID);
3684         RT_TRACE(COMP_INIT, "EEPROM ChannelPlan = 0x%4x\n", priv->eeprom_ChannelPlan);
3685         RT_TRACE(COMP_INIT, "bIgnoreDiffRateTxPowerOffset = %d\n", priv->bIgnoreDiffRateTxPowerOffset);
3686
3687
3688         // Read USB optional function.
3689         if(!priv->AutoloadFailFlag)
3690         {
3691                 priv->EEPROMUsbOption = *(u8 *)&hwinfo[EEPROM_USB_OPTIONAL];
3692         }
3693         else
3694         {
3695                 priv->EEPROMUsbOption = EEPROM_USB_Default_OPTIONAL_FUNC;
3696         }
3697
3698
3699         priv->EEPROMUsbEndPointNumber = rtl8192SU_UsbOptionToEndPointNumber((priv->EEPROMUsbOption&EEPROM_EP_NUMBER)>>3);
3700
3701         RT_TRACE(COMP_INIT, "USB Option = %#x\n", priv->EEPROMUsbOption);
3702         RT_TRACE(COMP_INIT, "EndPoint Number = %#x\n", priv->EEPROMUsbEndPointNumber);
3703
3704 #ifdef TO_DO_LIST
3705         //
3706         //  Decide CustomerID according to VID/DID or EEPROM
3707         //
3708         switch(pHalData->EEPROMCustomerID)
3709         {
3710                 case EEPROM_CID_ALPHA:
3711                         pMgntInfo->CustomerID = RT_CID_819x_ALPHA;
3712                         break;
3713
3714                 case EEPROM_CID_CAMEO:
3715                         pMgntInfo->CustomerID = RT_CID_819x_CAMEO;
3716                         break;
3717
3718                 case EEPROM_CID_SITECOM:
3719                         pMgntInfo->CustomerID = RT_CID_819x_Sitecom;
3720                         RT_TRACE(COMP_INIT, DBG_LOUD, ("CustomerID = 0x%4x\n", pMgntInfo->CustomerID));
3721
3722                         break;
3723
3724                 case EEPROM_CID_WHQL:
3725                         Adapter->bInHctTest = TRUE;
3726
3727                         pMgntInfo->bSupportTurboMode = FALSE;
3728                         pMgntInfo->bAutoTurboBy8186 = FALSE;
3729
3730                         pMgntInfo->PowerSaveControl.bInactivePs = FALSE;
3731                         pMgntInfo->PowerSaveControl.bIPSModeBackup = FALSE;
3732                         pMgntInfo->PowerSaveControl.bLeisurePs = FALSE;
3733                         pMgntInfo->keepAliveLevel = 0;
3734                         break;
3735
3736                 default:
3737                         pMgntInfo->CustomerID = RT_CID_DEFAULT;
3738                         break;
3739
3740         }
3741
3742         //
3743         // Led mode
3744         //
3745         switch(pMgntInfo->CustomerID)
3746         {
3747                 case RT_CID_DEFAULT:
3748                 case RT_CID_819x_ALPHA:
3749                         pHalData->LedStrategy = SW_LED_MODE1;
3750                         pHalData->bRegUseLed = TRUE;
3751                         pHalData->SwLed1.bLedOn = TRUE;
3752                         break;
3753                 case RT_CID_819x_CAMEO:
3754                         pHalData->LedStrategy = SW_LED_MODE1;
3755                         pHalData->bRegUseLed = TRUE;
3756                         break;
3757
3758                 case RT_CID_819x_Sitecom:
3759                         pHalData->LedStrategy = SW_LED_MODE2;
3760                         pHalData->bRegUseLed = TRUE;
3761                         break;
3762
3763                 default:
3764                         pHalData->LedStrategy = SW_LED_MODE0;
3765                         break;
3766         }
3767 #endif
3768
3769         // Read USB PHY parameters.
3770         for(i=0; i<5; i++)
3771                 priv->EEPROMUsbPhyParam[i] = *(u8 *)&hwinfo[EEPROM_USB_PHY_PARA1+i];
3772
3773         //RT_PRINT_DATA(COMP_EFUSE, DBG_LOUD, ("USB PHY Param: \n"), pHalData->EEPROMUsbPhyParam, 5);
3774
3775
3776        //Read Permanent MAC address
3777         for(i=0; i<6; i++)
3778                 dev->dev_addr[i] =  *(u8 *)&hwinfo[EEPROM_NODE_ADDRESS_BYTE_0+i];
3779
3780         //NicIFSetMacAddress(Adapter, Adapter->PermanentAddress);
3781         write_nic_dword(dev, IDR0, ((u32*)dev->dev_addr)[0]);
3782         write_nic_word(dev, IDR4, ((u16*)(dev->dev_addr + 4))[0]);
3783
3784         RT_TRACE(COMP_INIT,
3785                 "ReadAdapterInfo8192SEFuse(), Permanent Address = %pM\n",
3786                 dev->dev_addr);
3787
3788         //
3789         // Get CustomerID(Boad Type)
3790         // i.e., 0x0: RTL8188SU, 0x1: RTL8191SU, 0x2: RTL8192SU, 0x3: RTL8191GU.
3791         // Others: Reserved. Default is 0x2: RTL8192SU.
3792         //
3793         //if(!priv->AutoloadFailFlag)
3794         //{
3795                 priv->EEPROMBoardType = *(u8 *)&hwinfo[EEPROM_BoardType];
3796                 priv->rf_type = rtl8192SU_BoardTypeToRFtype(dev, priv->EEPROMBoardType);
3797         //}
3798         //else
3799         //{
3800         //      priv->EEPROMBoardType = EEPROM_Default_BoardType;
3801         //      priv->rf_type = RF_1T2R;
3802         //}
3803
3804         priv->rf_chip = RF_6052;
3805
3806         priv->rf_chip = RF_6052;//lzm test
3807         RT_TRACE(COMP_INIT, "BoardType = 0x%2x\n", priv->EEPROMBoardType);
3808         RT_TRACE(COMP_INIT, "RF_Type = 0x%2x\n", priv->rf_type);
3809
3810         //
3811         // Read antenna tx power offset of B/C/D to A  from EEPROM
3812         // and read ThermalMeter from EEPROM
3813         //
3814         //if(!priv->AutoloadFailFlag)
3815         {
3816                 priv->EEPROMTxPowerDiff = *(u8 *)&hwinfo[EEPROM_PwDiff];
3817                 priv->EEPROMThermalMeter = *(u8 *)&hwinfo[EEPROM_ThermalMeter];
3818         }
3819         //else
3820         //{
3821         //      priv->EEPROMTxPowerDiff = EEPROM_Default_PwDiff;
3822         //      priv->EEPROMThermalMeter = EEPROM_Default_ThermalMeter;
3823         //}
3824
3825         RT_TRACE(COMP_INIT, "PwDiff = %#x\n", priv->EEPROMTxPowerDiff);
3826         RT_TRACE(COMP_INIT, "ThermalMeter = %#x\n", priv->EEPROMThermalMeter);
3827
3828         //
3829         // Read Tx Power gain offset of legacy OFDM to HT rate.
3830         // Read CrystalCap from EEPROM
3831         //
3832         //if(!priv->AutoloadFailFlag)
3833         {
3834                 priv->EEPROMCrystalCap = *(u8 *)&hwinfo[EEPROM_CrystalCap];
3835         }
3836         //else
3837         //{
3838         //      priv->EEPROMCrystalCap = EEPROM_Default_CrystalCap;
3839         //}
3840
3841         RT_TRACE(COMP_INIT, "CrystalCap = %#x\n", priv->EEPROMCrystalCap);
3842
3843         //
3844         // Get Tx Power Base.
3845         //
3846         //if(!priv->AutoloadFailFlag)
3847         {
3848                 priv->EEPROMTxPwrBase = *(u8 *)&hwinfo[EEPROM_TxPowerBase];
3849         }
3850         //else
3851         //{
3852         //      priv->EEPROMTxPwrBase = EEPROM_Default_TxPowerBase;
3853         //}
3854
3855         RT_TRACE(COMP_INIT, "TxPwrBase = %#x\n", priv->EEPROMTxPwrBase);
3856
3857
3858         //
3859         // Get TSSI value for each path.
3860         //
3861         //if(!priv->AutoloadFailFlag)
3862         {
3863                 priv->EEPROMTSSI_A = *(u8 *)&hwinfo[EEPROM_TSSI_A];
3864                 priv->EEPROMTSSI_B = *(u8 *)&hwinfo[EEPROM_TSSI_B];
3865         }
3866         //else
3867         //{ // Default setting for Empty EEPROM
3868         //      priv->EEPROMTSSI_A = EEPROM_Default_TSSI;
3869         //      priv->EEPROMTSSI_B = EEPROM_Default_TSSI;
3870         //}
3871
3872         RT_TRACE(COMP_INIT, "TSSI_A = %#x, TSSI_B = %#x\n", priv->EEPROMTSSI_A, priv->EEPROMTSSI_B);
3873
3874         //
3875         // Get Tx Power tracking mode.
3876         //
3877         //if(!priv->AutoloadFailFlag)
3878         {
3879                 priv->EEPROMTxPwrTkMode = *(u8 *)&hwinfo[EEPROM_TxPwTkMode];
3880         }
3881
3882         RT_TRACE(COMP_INIT, "TxPwrTkMod = %#x\n", priv->EEPROMTxPwrTkMode);
3883
3884
3885         {
3886                 //
3887                 // Buffer TxPwIdx(i.e., from offset 0x55~0x66, total 18Bytes)
3888                 // Update CCK, OFDM (1T/2T)Tx Power Index from above buffer.
3889                 //
3890
3891                 //
3892                 // Get Tx Power Level by Channel
3893                 //
3894                 //if(!priv->AutoloadFailFlag)
3895                 {
3896                         // Read Tx power of Channel 1 ~ 14 from EFUSE.
3897                         // 92S suupport RF A & B
3898                         for (rf_path = 0; rf_path < 2; rf_path++)
3899                         {
3900                                 for (i = 0; i < 3; i++)
3901                                 {
3902                                         // Read CCK RF A & B Tx power
3903                                         priv->RfCckChnlAreaTxPwr[rf_path][i] =
3904                                         hwinfo[EEPROM_TxPwIndex+rf_path*3+i];
3905
3906                                         // Read OFDM RF A & B Tx power for 1T
3907                                         priv->RfOfdmChnlAreaTxPwr1T[rf_path][i] =
3908                                         hwinfo[EEPROM_TxPwIndex+6+rf_path*3+i];
3909
3910                                         // Read OFDM RF A & B Tx power for 2T
3911                                         priv->RfOfdmChnlAreaTxPwr2T[rf_path][i] =
3912                                         hwinfo[EEPROM_TxPwIndex+12+rf_path*3+i];
3913                                 }
3914                         }
3915
3916                 }
3917                 update_hal_variables(priv);
3918         }
3919
3920         //
3921         // 2009/02/09 Cosa add for new EEPROM format
3922         //
3923         for(i=0; i<14; i++)     // channel 1~3 use the same Tx Power Level.
3924         {
3925                 // Read tx power difference between HT OFDM 20/40 MHZ
3926                 if (i < 3)                      // Cjanel 1-3
3927                         index = 0;
3928                 else if (i < 9)         // Channel 4-9
3929                         index = 1;
3930                 else                            // Channel 10-14
3931                         index = 2;
3932
3933                 tempval = (*(u8 *)&hwinfo[EEPROM_TX_PWR_HT20_DIFF+index])&0xff;
3934                 priv->TxPwrHt20Diff[RF90_PATH_A][i] = (tempval&0xF);
3935                 priv->TxPwrHt20Diff[RF90_PATH_B][i] = ((tempval>>4)&0xF);
3936
3937                 // Read OFDM<->HT tx power diff
3938                 if (i < 3)                      // Cjanel 1-3
3939                         tempval = (*(u8 *)&hwinfo[EEPROM_TX_PWR_OFDM_DIFF])&0xff;
3940                 else if (i < 9)         // Channel 4-9
3941                         tempval = (*(u8 *)&hwinfo[EEPROM_PwDiff])&0xff;
3942                 else                            // Channel 10-14
3943                         tempval = (*(u8 *)&hwinfo[EEPROM_TX_PWR_OFDM_DIFF+1])&0xff;
3944
3945                 //cosa tempval = (*(u1Byte *)&hwinfo[EEPROM_TX_PWR_OFDM_DIFF+index])&0xff;
3946                 priv->TxPwrLegacyHtDiff[RF90_PATH_A][i] = (tempval&0xF);
3947                 priv->TxPwrLegacyHtDiff[RF90_PATH_B][i] = ((tempval>>4)&0xF);
3948
3949                 //
3950                 // Read Band Edge tx power offset and check if user enable the ability
3951                 //
3952                 // HT 40 band edge channel
3953                 tempval = (*(u8 *)&hwinfo[EEPROM_TX_PWR_BAND_EDGE])&0xff;
3954                 priv->TxPwrbandEdgeHt40[RF90_PATH_A][0] = (tempval&0xF);                // Band edge low channel
3955                 priv->TxPwrbandEdgeHt40[RF90_PATH_A][1] =  ((tempval>>4)&0xF);  // Band edge high channel
3956                 tempval = (*(u8 *)&hwinfo[EEPROM_TX_PWR_BAND_EDGE+1])&0xff;
3957                 priv->TxPwrbandEdgeHt40[RF90_PATH_B][0] = (tempval&0xF);                // Band edge low channel
3958                 priv->TxPwrbandEdgeHt40[RF90_PATH_B][1] =  ((tempval>>4)&0xF);  // Band edge high channel
3959                 // HT 20 band edge channel
3960                 tempval = (*(u8 *)&hwinfo[EEPROM_TX_PWR_BAND_EDGE+2])&0xff;
3961                 priv->TxPwrbandEdgeHt20[RF90_PATH_A][0] = (tempval&0xF);                // Band edge low channel
3962                 priv->TxPwrbandEdgeHt20[RF90_PATH_A][1] =  ((tempval>>4)&0xF);  // Band edge high channel
3963                 tempval = (*(u8 *)&hwinfo[EEPROM_TX_PWR_BAND_EDGE+3])&0xff;
3964                 priv->TxPwrbandEdgeHt20[RF90_PATH_B][0] = (tempval&0xF);                // Band edge low channel
3965                 priv->TxPwrbandEdgeHt20[RF90_PATH_B][1] =  ((tempval>>4)&0xF);  // Band edge high channel
3966                 // OFDM band edge channel
3967                 tempval = (*(u8 *)&hwinfo[EEPROM_TX_PWR_BAND_EDGE+4])&0xff;
3968                 priv->TxPwrbandEdgeLegacyOfdm[RF90_PATH_A][0] = (tempval&0xF);          // Band edge low channel
3969                 priv->TxPwrbandEdgeLegacyOfdm[RF90_PATH_A][1] =  ((tempval>>4)&0xF);    // Band edge high channel
3970                 tempval = (*(u8 *)&hwinfo[EEPROM_TX_PWR_BAND_EDGE+5])&0xff;
3971                 priv->TxPwrbandEdgeLegacyOfdm[RF90_PATH_B][0] = (tempval&0xF);          // Band edge low channel
3972                 priv->TxPwrbandEdgeLegacyOfdm[RF90_PATH_B][1] =  ((tempval>>4)&0xF);    // Band edge high channel
3973
3974                 priv->TxPwrbandEdgeFlag = (*(u8 *)&hwinfo[TX_PWR_BAND_EDGE_CHK]);
3975         }
3976
3977         for(i=0; i<14; i++)
3978                 RT_TRACE(COMP_INIT, "RF-A Ht20 to HT40 Diff[%d] = 0x%x\n", i, priv->TxPwrHt20Diff[RF90_PATH_A][i]);
3979         for(i=0; i<14; i++)
3980                 RT_TRACE(COMP_INIT,  "RF-A Legacy to Ht40 Diff[%d] = 0x%x\n", i, priv->TxPwrLegacyHtDiff[RF90_PATH_A][i]);
3981         for(i=0; i<14; i++)
3982                 RT_TRACE(COMP_INIT,  "RF-B Ht20 to HT40 Diff[%d] = 0x%x\n", i, priv->TxPwrHt20Diff[RF90_PATH_B][i]);
3983         for(i=0; i<14; i++)
3984                 RT_TRACE(COMP_INIT,  "RF-B Legacy to HT40 Diff[%d] = 0x%x\n", i, priv->TxPwrLegacyHtDiff[RF90_PATH_B][i]);
3985         RT_TRACE(COMP_INIT, "RF-A HT40 band-edge low/high power diff = 0x%x/0x%x\n",
3986                 priv->TxPwrbandEdgeHt40[RF90_PATH_A][0],
3987                 priv->TxPwrbandEdgeHt40[RF90_PATH_A][1]);
3988         RT_TRACE((COMP_INIT&COMP_DBG), "RF-B HT40 band-edge low/high power diff = 0x%x/0x%x\n",
3989                 priv->TxPwrbandEdgeHt40[RF90_PATH_B][0],
3990                 priv->TxPwrbandEdgeHt40[RF90_PATH_B][1]);
3991
3992         RT_TRACE((COMP_INIT&COMP_DBG), "RF-A HT20 band-edge low/high power diff = 0x%x/0x%x\n",
3993                 priv->TxPwrbandEdgeHt20[RF90_PATH_A][0],
3994                 priv->TxPwrbandEdgeHt20[RF90_PATH_A][1]);
3995         RT_TRACE((COMP_INIT&COMP_DBG), "RF-B HT20 band-edge low/high power diff = 0x%x/0x%x\n",
3996                 priv->TxPwrbandEdgeHt20[RF90_PATH_B][0],
3997                 priv->TxPwrbandEdgeHt20[RF90_PATH_B][1]);
3998
3999         RT_TRACE((COMP_INIT&COMP_DBG), "RF-A OFDM band-edge low/high power diff = 0x%x/0x%x\n",
4000                 priv->TxPwrbandEdgeLegacyOfdm[RF90_PATH_A][0],
4001                 priv->TxPwrbandEdgeLegacyOfdm[RF90_PATH_A][1]);
4002         RT_TRACE((COMP_INIT&COMP_DBG), "RF-B OFDM band-edge low/high power diff = 0x%x/0x%x\n",
4003                 priv->TxPwrbandEdgeLegacyOfdm[RF90_PATH_B][0],
4004                 priv->TxPwrbandEdgeLegacyOfdm[RF90_PATH_B][1]);
4005         RT_TRACE((COMP_INIT&COMP_DBG), "Band-edge enable flag = %d\n", priv->TxPwrbandEdgeFlag);
4006
4007         //
4008         // Update remained HAL variables.
4009         //
4010         priv->TSSI_13dBm = priv->EEPROMThermalMeter *100;
4011         priv->LegacyHTTxPowerDiff = priv->EEPROMTxPowerDiff;
4012         priv->TxPowerDiff = priv->EEPROMTxPowerDiff;
4013         //priv->AntennaTxPwDiff[0] = (priv->EEPROMTxPowerDiff & 0xf);// Antenna B gain offset to antenna A, bit[3:0]
4014         //priv->AntennaTxPwDiff[1] = ((priv->EEPROMTxPowerDiff & 0xf0)>>4);// Antenna C gain offset to antenna A, bit[7:4]
4015         priv->CrystalCap = priv->EEPROMCrystalCap;      // CrystalCap, bit[15:12]
4016         priv->ThermalMeter[0] = (priv->EEPROMThermalMeter&0x1f);// ThermalMeter, bit0~3 for RFIC1, bit4~7 for RFIC2
4017         priv->LedStrategy = SW_LED_MODE0;
4018
4019         init_rate_adaptive(dev);
4020
4021         RT_TRACE(COMP_INIT, "<==== ReadAdapterInfo8192SUsb\n");
4022
4023         //return RT_STATUS_SUCCESS;
4024 }
4025
4026
4027 //
4028 //      Description:
4029 //              Read HW adapter information by E-Fuse or EEPROM according CR9346 reported.
4030 //
4031 //      Assumption:
4032 //              1. CR9346 regiser has verified.
4033 //              2. PASSIVE_LEVEL (USB interface)
4034 //
4035 //      Created by Roger, 2008.10.21.
4036 //
4037 static void rtl8192SU_read_eeprom_info(struct net_device *dev)
4038 {
4039         struct r8192_priv       *priv = ieee80211_priv(dev);
4040         u8                      tmpU1b;
4041
4042         RT_TRACE(COMP_INIT, "====> ReadAdapterInfo8192SUsb\n");
4043
4044         // Retrieve Chip version.
4045         priv->card_8192_version = (VERSION_8192S)((read_nic_dword(dev, PMC_FSM)>>16)&0xF);
4046         RT_TRACE(COMP_INIT, "Chip Version ID: 0x%2x\n", priv->card_8192_version);
4047
4048         tmpU1b = read_nic_byte(dev, EPROM_CMD);//CR9346
4049
4050         // To check system boot selection.
4051         if (tmpU1b & CmdEERPOMSEL)
4052         {
4053                 RT_TRACE(COMP_INIT, "Boot from EEPROM\n");
4054                 priv->EepromOrEfuse = TRUE;
4055         }
4056         else
4057         {
4058                 RT_TRACE(COMP_INIT, "Boot from EFUSE\n");
4059                 priv->EepromOrEfuse = FALSE;
4060         }
4061
4062         // To check autoload success or not.
4063         if (tmpU1b & CmdEEPROM_En)
4064         {
4065                 RT_TRACE(COMP_INIT, "Autoload OK!!\n");
4066                 priv->AutoloadFailFlag=FALSE;
4067                 rtl8192SU_ReadAdapterInfo8192SUsb(dev);//eeprom or e-fuse
4068         }
4069         else
4070         { // Auto load fail.
4071                 RT_TRACE(COMP_INIT, "AutoLoad Fail reported from CR9346!!\n");
4072                 priv->AutoloadFailFlag=TRUE;
4073                 rtl8192SU_ConfigAdapterInfo8192SForAutoLoadFail(dev);
4074
4075                 //if (IS_BOOT_FROM_EFUSE(Adapter))
4076                 if(!priv->EepromOrEfuse)
4077                 {
4078                         RT_TRACE(COMP_INIT, "Update shadow map for EFuse future use!!\n");
4079                         EFUSE_ShadowMapUpdate(dev);
4080                 }
4081         }
4082 #ifdef TO_DO_LIST
4083         if((priv->RegChannelPlan >= RT_CHANNEL_DOMAIN_MAX) || (pHalData->EEPROMChannelPlan & EEPROM_CHANNEL_PLAN_BY_HW_MASK))
4084         {
4085                 pMgntInfo->ChannelPlan = HalMapChannelPlan8192S(Adapter, (pHalData->EEPROMChannelPlan & (~(EEPROM_CHANNEL_PLAN_BY_HW_MASK))));
4086                 pMgntInfo->bChnlPlanFromHW = (pHalData->EEPROMChannelPlan & EEPROM_CHANNEL_PLAN_BY_HW_MASK) ? TRUE : FALSE; // User cannot change  channel plan.
4087         }
4088         else
4089         {
4090                 pMgntInfo->ChannelPlan = (RT_CHANNEL_DOMAIN)pMgntInfo->RegChannelPlan;
4091         }
4092
4093         switch(pMgntInfo->ChannelPlan)
4094         {
4095                 case RT_CHANNEL_DOMAIN_GLOBAL_DOAMIN:
4096                 {
4097                         PRT_DOT11D_INFO pDot11dInfo = GET_DOT11D_INFO(pMgntInfo);
4098
4099                         pDot11dInfo->bEnabled = TRUE;
4100                 }
4101                 RT_TRACE(COMP_INIT, DBG_LOUD, ("ReadAdapterInfo8187(): Enable dot11d when RT_CHANNEL_DOMAIN_GLOBAL_DOAMIN!\n"));
4102                 break;
4103         }
4104
4105         RT_TRACE(COMP_INIT, DBG_LOUD, ("RegChannelPlan(%d) EEPROMChannelPlan(%d)", pMgntInfo->RegChannelPlan, pHalData->EEPROMChannelPlan));
4106         RT_TRACE(COMP_INIT, DBG_LOUD, ("ChannelPlan = %d\n" , pMgntInfo->ChannelPlan));
4107
4108         RT_TRACE(COMP_INIT, DBG_LOUD, ("<==== ReadAdapterInfo8192S\n"));
4109 #endif
4110
4111         RT_TRACE(COMP_INIT, "<==== ReadAdapterInfo8192SUsb\n");
4112
4113         //return RT_STATUS_SUCCESS;
4114 }
4115
4116 short rtl8192_get_channel_map(struct net_device * dev)
4117 {
4118         struct r8192_priv *priv = ieee80211_priv(dev);
4119         if(priv->ChannelPlan > COUNTRY_CODE_GLOBAL_DOMAIN){
4120                 printk("rtl8180_init:Error channel plan! Set to default.\n");
4121                 priv->ChannelPlan= 0;
4122         }
4123         RT_TRACE(COMP_INIT, "Channel plan is %d\n",priv->ChannelPlan);
4124
4125         rtl819x_set_channel_map(priv->ChannelPlan, priv);
4126         return 0;
4127 }
4128
4129 short rtl8192_init(struct net_device *dev)
4130 {
4131
4132         struct r8192_priv *priv = ieee80211_priv(dev);
4133
4134         rtl8192_init_priv_variable(dev);
4135         rtl8192_init_priv_lock(priv);
4136         rtl8192_init_priv_task(dev);
4137         rtl8192_get_eeprom_size(dev);
4138         priv->ops->rtl819x_read_eeprom_info(dev);
4139         rtl8192_get_channel_map(dev);
4140         init_hal_dm(dev);
4141         init_timer(&priv->watch_dog_timer);
4142         priv->watch_dog_timer.data = (unsigned long)dev;
4143         priv->watch_dog_timer.function = watch_dog_timer_callback;
4144
4145         //rtl8192_adapter_start(dev);
4146 #ifdef DEBUG_EPROM
4147         dump_eprom(dev);
4148 #endif
4149         return 0;
4150 }
4151
4152 /******************************************************************************
4153  *function:  This function actually only set RRSR, RATR and BW_OPMODE registers
4154  *           not to do all the hw config as its name says
4155  *   input:  net_device dev
4156  *  output:  none
4157  *  return:  none
4158  *  notice:  This part need to modified according to the rate set we filtered
4159  * ****************************************************************************/
4160 void rtl8192_hwconfig(struct net_device* dev)
4161 {
4162         u32 regRATR = 0, regRRSR = 0;
4163         u8 regBwOpMode = 0, regTmp = 0;
4164         struct r8192_priv *priv = ieee80211_priv(dev);
4165
4166 // Set RRSR, RATR, and BW_OPMODE registers
4167         //
4168         switch(priv->ieee80211->mode)
4169         {
4170         case WIRELESS_MODE_B:
4171                 regBwOpMode = BW_OPMODE_20MHZ;
4172                 regRATR = RATE_ALL_CCK;
4173                 regRRSR = RATE_ALL_CCK;
4174                 break;
4175         case WIRELESS_MODE_A:
4176                 regBwOpMode = BW_OPMODE_5G |BW_OPMODE_20MHZ;
4177                 regRATR = RATE_ALL_OFDM_AG;
4178                 regRRSR = RATE_ALL_OFDM_AG;
4179                 break;
4180         case WIRELESS_MODE_G:
4181                 regBwOpMode = BW_OPMODE_20MHZ;
4182                 regRATR = RATE_ALL_CCK | RATE_ALL_OFDM_AG;
4183                 regRRSR = RATE_ALL_CCK | RATE_ALL_OFDM_AG;
4184                 break;
4185         case WIRELESS_MODE_AUTO:
4186 #ifdef TO_DO_LIST
4187                 if (Adapter->bInHctTest)
4188                 {
4189                     regBwOpMode = BW_OPMODE_20MHZ;
4190                     regRATR = RATE_ALL_CCK | RATE_ALL_OFDM_AG;
4191                     regRRSR = RATE_ALL_CCK | RATE_ALL_OFDM_AG;
4192                 }
4193                 else
4194 #endif
4195                 {
4196                     regBwOpMode = BW_OPMODE_20MHZ;
4197                     regRATR = RATE_ALL_CCK | RATE_ALL_OFDM_AG | RATE_ALL_OFDM_1SS | RATE_ALL_OFDM_2SS;
4198                     regRRSR = RATE_ALL_CCK | RATE_ALL_OFDM_AG;
4199                 }
4200                 break;
4201         case WIRELESS_MODE_N_24G:
4202                 // It support CCK rate by default.
4203                 // CCK rate will be filtered out only when associated AP does not support it.
4204                 regBwOpMode = BW_OPMODE_20MHZ;
4205                         regRATR = RATE_ALL_CCK | RATE_ALL_OFDM_AG | RATE_ALL_OFDM_1SS | RATE_ALL_OFDM_2SS;
4206                         regRRSR = RATE_ALL_CCK | RATE_ALL_OFDM_AG;
4207                 break;
4208         case WIRELESS_MODE_N_5G:
4209                 regBwOpMode = BW_OPMODE_5G;
4210                 regRATR = RATE_ALL_OFDM_AG | RATE_ALL_OFDM_1SS | RATE_ALL_OFDM_2SS;
4211                 regRRSR = RATE_ALL_OFDM_AG;
4212                 break;
4213         }
4214
4215         write_nic_byte(dev, BW_OPMODE, regBwOpMode);
4216         {
4217                 u32 ratr_value = 0;
4218                 ratr_value = regRATR;
4219                 if (priv->rf_type == RF_1T2R)
4220                 {
4221                         ratr_value &= ~(RATE_ALL_OFDM_2SS);
4222                 }
4223                 write_nic_dword(dev, RATR0, ratr_value);
4224                 write_nic_byte(dev, UFWP, 1);
4225         }
4226         regTmp = read_nic_byte(dev, 0x313);
4227         regRRSR = ((regTmp) << 24) | (regRRSR & 0x00ffffff);
4228         write_nic_dword(dev, RRSR, regRRSR);
4229
4230         //
4231         // Set Retry Limit here
4232         //
4233         write_nic_word(dev, RETRY_LIMIT,
4234                         priv->ShortRetryLimit << RETRY_LIMIT_SHORT_SHIFT | \
4235                         priv->LongRetryLimit << RETRY_LIMIT_LONG_SHIFT);
4236         // Set Contention Window here
4237
4238         // Set Tx AGC
4239
4240         // Set Tx Antenna including Feedback control
4241
4242         // Set Auto Rate fallback control
4243
4244
4245 }
4246
4247
4248 //
4249 //      Description:
4250 //              Initial HW relted registers.
4251 //
4252 //      Assumption:
4253 //              Config RTL8192S USB MAC, we should config MAC before download FW.
4254 //
4255 //      2008.09.03, Added by Roger.
4256 //
4257 static void rtl8192SU_MacConfigBeforeFwDownloadASIC(struct net_device *dev)
4258 {
4259         u8                              tmpU1b;// i;
4260 //      u16                             tmpU2b;
4261 //      u32                             tmpU4b;
4262         u8                              PollingCnt = 20;
4263
4264         RT_TRACE(COMP_INIT, "--->MacConfigBeforeFwDownloadASIC()\n");
4265
4266         //2MAC Initialization for power on sequence, Revised by Roger. 2008.09.03.
4267
4268         //
4269         //<Roger_Notes> Set control path switch to HW control and reset Digital Core,  CPU Core and
4270         // MAC I/O to solve FW download fail when system from resume sate.
4271         // 2008.11.04.
4272         //
4273        tmpU1b = read_nic_byte(dev, SYS_CLKR+1);
4274        if(tmpU1b & 0x80)
4275         {
4276         tmpU1b &= 0x3f;
4277               write_nic_byte(dev, SYS_CLKR+1, tmpU1b);
4278        }
4279         // Clear FW RPWM for FW control LPS. by tynli. 2009.02.23
4280         write_nic_byte(dev, RPWM, 0x0);
4281
4282        tmpU1b = read_nic_byte(dev, SYS_FUNC_EN+1);
4283        tmpU1b &= 0x73;
4284        write_nic_byte(dev, SYS_FUNC_EN+1, tmpU1b);
4285        udelay(1000);
4286
4287         //Revised POS, suggested by SD1 Alex, 2008.09.27.
4288         write_nic_byte(dev, SPS0_CTRL+1, 0x53);
4289         write_nic_byte(dev, SPS0_CTRL, 0x57);
4290
4291         //Enable AFE Macro Block's Bandgap adn Enable AFE Macro Block's Mbias
4292         tmpU1b = read_nic_byte(dev, AFE_MISC);
4293         write_nic_byte(dev, AFE_MISC, (tmpU1b|AFE_BGEN|AFE_MBEN));
4294
4295         //Enable PLL Power (LDOA15V)
4296         tmpU1b = read_nic_byte(dev, LDOA15_CTRL);
4297         write_nic_byte(dev, LDOA15_CTRL, (tmpU1b|LDA15_EN));
4298
4299         //Enable LDOV12D block
4300         tmpU1b = read_nic_byte(dev, LDOV12D_CTRL);
4301         write_nic_byte(dev, LDOV12D_CTRL, (tmpU1b|LDV12_EN));
4302
4303         //mpU1b = read_nic_byte(Adapter, SPS1_CTRL);
4304         //write_nic_byte(dev, SPS1_CTRL, (tmpU1b|SPS1_LDEN));
4305
4306         //PlatformSleepUs(2000);
4307
4308         //Enable Switch Regulator Block
4309         //tmpU1b = read_nic_byte(Adapter, SPS1_CTRL);
4310         //write_nic_byte(dev, SPS1_CTRL, (tmpU1b|SPS1_SWEN));
4311
4312         //write_nic_dword(Adapter, SPS1_CTRL, 0x00a7b267);
4313
4314         tmpU1b = read_nic_byte(dev, SYS_ISO_CTRL+1);
4315         write_nic_byte(dev, SYS_ISO_CTRL+1, (tmpU1b|0x08));
4316
4317         //Engineer Packet CP test Enable
4318         tmpU1b = read_nic_byte(dev, SYS_FUNC_EN+1);
4319         write_nic_byte(dev, SYS_FUNC_EN+1, (tmpU1b|0x20));
4320
4321         //Support 64k IMEM, suggested by SD1 Alex.
4322         tmpU1b = read_nic_byte(dev, SYS_ISO_CTRL+1);
4323         write_nic_byte(dev, SYS_ISO_CTRL+1, (tmpU1b& 0x68));
4324
4325         //Enable AFE clock
4326         tmpU1b = read_nic_byte(dev, AFE_XTAL_CTRL+1);
4327         write_nic_byte(dev, AFE_XTAL_CTRL+1, (tmpU1b& 0xfb));
4328
4329         //Enable AFE PLL Macro Block
4330         tmpU1b = read_nic_byte(dev, AFE_PLL_CTRL);
4331         write_nic_byte(dev, AFE_PLL_CTRL, (tmpU1b|0x11));
4332
4333         //Attatch AFE PLL to MACTOP/BB/PCIe Digital
4334         tmpU1b = read_nic_byte(dev, SYS_ISO_CTRL);
4335         write_nic_byte(dev, SYS_ISO_CTRL, (tmpU1b&0xEE));
4336
4337         // Switch to 40M clock
4338         write_nic_byte(dev, SYS_CLKR, 0x00);
4339
4340         //SSC Disable
4341         tmpU1b = read_nic_byte(dev, SYS_CLKR);
4342         //write_nic_byte(dev, SYS_CLKR, (tmpU1b&0x5f));
4343         write_nic_byte(dev, SYS_CLKR, (tmpU1b|0xa0));
4344
4345         //Enable MAC clock
4346         tmpU1b = read_nic_byte(dev, SYS_CLKR+1);
4347         write_nic_byte(dev, SYS_CLKR+1, (tmpU1b|0x18));
4348
4349         //Revised POS, suggested by SD1 Alex, 2008.09.27.
4350         write_nic_byte(dev, PMC_FSM, 0x02);
4351
4352         //Enable Core digital and enable IOREG R/W
4353         tmpU1b = read_nic_byte(dev, SYS_FUNC_EN+1);
4354         write_nic_byte(dev, SYS_FUNC_EN+1, (tmpU1b|0x08));
4355
4356         //Enable REG_EN
4357         tmpU1b = read_nic_byte(dev, SYS_FUNC_EN+1);
4358         write_nic_byte(dev, SYS_FUNC_EN+1, (tmpU1b|0x80));
4359
4360         //Switch the control path to FW
4361         tmpU1b = read_nic_byte(dev, SYS_CLKR+1);
4362         write_nic_byte(dev, SYS_CLKR+1, (tmpU1b|0x80)& 0xBF);
4363
4364         write_nic_byte(dev, CMDR, 0xFC);
4365         write_nic_byte(dev, CMDR+1, 0x37);
4366
4367         //Fix the RX FIFO issue(usb error), 970410
4368         tmpU1b = read_nic_byte_E(dev, 0x5c);
4369         write_nic_byte_E(dev, 0x5c, (tmpU1b|BIT7));
4370
4371          //For power save, used this in the bit file after 970621
4372         tmpU1b = read_nic_byte(dev, SYS_CLKR);
4373         write_nic_byte(dev, SYS_CLKR, tmpU1b&(~SYS_CPU_CLKSEL));
4374
4375         // Revised for 8051 ROM code wrong operation. Added by Roger. 2008.10.16.
4376         write_nic_byte_E(dev, 0x1c, 0x80);
4377
4378         //
4379         // <Roger_EXP> To make sure that TxDMA can ready to download FW.
4380         // We should reset TxDMA if IMEM RPT was not ready.
4381         // Suggested by SD1 Alex. 2008.10.23.
4382         //
4383         do
4384         {
4385                 tmpU1b = read_nic_byte(dev, TCR);
4386                 if((tmpU1b & TXDMA_INIT_VALUE) == TXDMA_INIT_VALUE)
4387                         break;
4388                 //PlatformStallExecution(5);
4389                 udelay(5);
4390         }while(PollingCnt--);   // Delay 1ms
4391
4392         if(PollingCnt <= 0 )
4393         {
4394                 RT_TRACE(COMP_INIT, "MacConfigBeforeFwDownloadASIC(): Polling TXDMA_INIT_VALUE timeout!! Current TCR(%#x)\n", tmpU1b);
4395                 tmpU1b = read_nic_byte(dev, CMDR);
4396                 write_nic_byte(dev, CMDR, tmpU1b&(~TXDMA_EN));
4397                 udelay(2);
4398                 write_nic_byte(dev, CMDR, tmpU1b|TXDMA_EN);// Reset TxDMA
4399         }
4400
4401
4402         RT_TRACE(COMP_INIT, "<---MacConfigBeforeFwDownloadASIC()\n");
4403 }
4404
4405 //
4406 //      Description:
4407 //              Initial HW relted registers.
4408 //
4409 //      Assumption:
4410 //              1. This function is only invoked at driver intialization once.
4411 //              2. PASSIVE LEVEL.
4412 //
4413 //      2008.06.10, Added by Roger.
4414 //
4415 static void rtl8192SU_MacConfigAfterFwDownload(struct net_device *dev)
4416 {
4417         struct r8192_priv *priv = ieee80211_priv((struct net_device *)dev);
4418         //PRT_HIGH_THROUGHPUT   pHTInfo = priv->ieee80211->pHTInfo;
4419         //u8    tmpU1b, RxPageCfg, i;
4420         u16     tmpU2b;
4421         u8      tmpU1b;//, i;
4422
4423
4424         RT_TRACE(COMP_INIT, "--->MacConfigAfterFwDownload()\n");
4425
4426         // Enable Tx/Rx
4427         tmpU2b = (BBRSTn|BB_GLB_RSTn|SCHEDULE_EN|MACRXEN|MACTXEN|DDMA_EN|
4428                          FW2HW_EN|RXDMA_EN|TXDMA_EN|HCI_RXDMA_EN|HCI_TXDMA_EN);         //3
4429         //Adapter->HalFunc.SetHwRegHandler( Adapter, HW_VAR_COMMAND, &tmpU1b );
4430         write_nic_word(dev, CMDR, tmpU2b); //LZM REGISTER COM 090305
4431
4432         // Loopback mode or not
4433         priv->LoopbackMode = RTL8192SU_NO_LOOPBACK; // Set no loopback as default.
4434         if(priv->LoopbackMode == RTL8192SU_NO_LOOPBACK)
4435                 tmpU1b = LBK_NORMAL;
4436         else if (priv->LoopbackMode == RTL8192SU_MAC_LOOPBACK )
4437                 tmpU1b = LBK_MAC_DLB;
4438         else
4439                 RT_TRACE(COMP_INIT, "Serious error: wrong loopback mode setting\n");
4440
4441         //Adapter->HalFunc.SetHwRegHandler( Adapter, HW_VAR_LBK_MODE, &tmpU1b);
4442         write_nic_byte(dev, LBKMD_SEL, tmpU1b);
4443
4444         // Set RCR
4445         write_nic_dword(dev, RCR, priv->ReceiveConfig);
4446         RT_TRACE(COMP_INIT, "MacConfigAfterFwDownload(): Current RCR settings(%#x)\n", priv->ReceiveConfig);
4447
4448
4449         // Set RQPN
4450         //
4451         // <Roger_Notes> 2008.08.18.
4452         // 6 endpoints:
4453         // (1) Page number on CMDQ is 0x03.
4454         // (2) Page number on BCNQ, HQ and MGTQ is 0.
4455         // (3) Page number on BKQ, BEQ, VIQ and VOQ are 0x07.
4456         // (4) Page number on PUBQ is 0xdd
4457         //
4458         // 11 endpoints:
4459         // (1) Page number on CMDQ is 0x00.
4460         // (2) Page number on BCNQ is 0x02, HQ and MGTQ are 0x03.
4461         // (3) Page number on BKQ, BEQ, VIQ and VOQ are 0x07.
4462         // (4) Page number on PUBQ is 0xd8
4463         //
4464         //write_nic_dword(Adapter, 0xa0, 0x07070707); //BKQ, BEQ, VIQ and VOQ
4465         //write_nic_byte(dev, 0xa4, 0x00); // HCCAQ
4466
4467         // Fix the RX FIFO issue(USB error), Rivesed by Roger, 2008-06-14
4468         tmpU1b = read_nic_byte_E(dev, 0x5C);
4469         write_nic_byte_E(dev, 0x5C, tmpU1b|BIT7);
4470
4471         // For EFUSE init configuration.
4472         //if (IS_BOOT_FROM_EFUSE(Adapter))      // We may R/W EFUSE in EFUSE mode
4473         if (priv->bBootFromEfuse)
4474         {
4475                 u8      tempval;
4476
4477                 tempval = read_nic_byte(dev, SYS_ISO_CTRL+1);
4478                 tempval &= 0xFE;
4479                 write_nic_byte(dev, SYS_ISO_CTRL+1, tempval);
4480
4481                 // Enable LDO 2.5V for write action
4482                 //tempval = read_nic_byte(Adapter, EFUSE_TEST+3);
4483                 //write_nic_byte(Adapter, EFUSE_TEST+3, (tempval | 0x80));
4484
4485                 // Change Efuse Clock for write action
4486                 //write_nic_byte(Adapter, EFUSE_CLK, 0x03);
4487
4488                 // Change Program timing
4489                 write_nic_byte(dev, EFUSE_CTRL+3, 0x72);
4490                 //printk("!!!!!!!!!!!!!!!!!!!!!%s: write 0x33 with 0x72\n",__FUNCTION__);
4491                 RT_TRACE(COMP_INIT, "EFUSE CONFIG OK\n");
4492         }
4493
4494
4495         RT_TRACE(COMP_INIT, "<---MacConfigAfterFwDownload()\n");
4496 }
4497
4498 void rtl8192SU_HwConfigureRTL8192SUsb(struct net_device *dev)
4499 {
4500
4501         struct r8192_priv *priv = ieee80211_priv(dev);
4502         u8                      regBwOpMode = 0;
4503         u32                     regRATR = 0, regRRSR = 0;
4504         u8                      regTmp = 0;
4505         u32                     i = 0;
4506
4507         //1 This part need to modified according to the rate set we filtered!!
4508         //
4509         // Set RRSR, RATR, and BW_OPMODE registers
4510         //
4511         switch(priv->ieee80211->mode)
4512         {
4513         case WIRELESS_MODE_B:
4514                 regBwOpMode = BW_OPMODE_20MHZ;
4515                 regRATR = RATE_ALL_CCK;
4516                 regRRSR = RATE_ALL_CCK;
4517                 break;
4518         case WIRELESS_MODE_A:
4519                 regBwOpMode = BW_OPMODE_5G |BW_OPMODE_20MHZ;
4520                 regRATR = RATE_ALL_OFDM_AG;
4521                 regRRSR = RATE_ALL_OFDM_AG;
4522                 break;
4523         case WIRELESS_MODE_G:
4524                 regBwOpMode = BW_OPMODE_20MHZ;
4525                 regRATR = RATE_ALL_CCK | RATE_ALL_OFDM_AG;
4526                 regRRSR = RATE_ALL_CCK | RATE_ALL_OFDM_AG;
4527                 break;
4528         case WIRELESS_MODE_AUTO:
4529                 if (priv->bInHctTest)
4530                 {
4531                     regBwOpMode = BW_OPMODE_20MHZ;
4532                     regRATR = RATE_ALL_CCK | RATE_ALL_OFDM_AG;
4533                     regRRSR = RATE_ALL_CCK | RATE_ALL_OFDM_AG;
4534                 }
4535                 else
4536                 {
4537                     regBwOpMode = BW_OPMODE_20MHZ;
4538                     regRATR = RATE_ALL_CCK | RATE_ALL_OFDM_AG | RATE_ALL_OFDM_1SS | RATE_ALL_OFDM_2SS;
4539                     regRRSR = RATE_ALL_CCK | RATE_ALL_OFDM_AG;
4540                 }
4541                 break;
4542         case WIRELESS_MODE_N_24G:
4543                 // It support CCK rate by default.
4544                 // CCK rate will be filtered out only when associated AP does not support it.
4545                 regBwOpMode = BW_OPMODE_20MHZ;
4546                         regRATR = RATE_ALL_CCK | RATE_ALL_OFDM_AG | RATE_ALL_OFDM_1SS | RATE_ALL_OFDM_2SS;
4547                         regRRSR = RATE_ALL_CCK | RATE_ALL_OFDM_AG;
4548                 break;
4549         case WIRELESS_MODE_N_5G:
4550                 regBwOpMode = BW_OPMODE_5G;
4551                 regRATR = RATE_ALL_OFDM_AG | RATE_ALL_OFDM_1SS | RATE_ALL_OFDM_2SS;
4552                 regRRSR = RATE_ALL_OFDM_AG;
4553                 break;
4554         }
4555
4556         //
4557         // <Roger_Notes> We disable CCK response rate until FIB CCK rate IC's back.
4558         // 2008.09.23.
4559         //
4560         regTmp = read_nic_byte(dev, INIRTSMCS_SEL);
4561         regRRSR = ((regRRSR & 0x000fffff)<<8) | regTmp;
4562
4563         //
4564         // Update SIFS timing.
4565         //
4566         //priv->SifsTime = 0x0e0e0a0a;
4567         //Adapter->HalFunc.SetHwRegHandler( Adapter, HW_VAR_SIFS,  (pu1Byte)&pHalData->SifsTime);
4568         {       u8 val[4] = {0x0e, 0x0e, 0x0a, 0x0a};
4569                 // SIFS for CCK Data ACK
4570                 write_nic_byte(dev, SIFS_CCK, val[0]);
4571                 // SIFS for CCK consecutive tx like CTS data!
4572                 write_nic_byte(dev, SIFS_CCK+1, val[1]);
4573
4574                 // SIFS for OFDM Data ACK
4575                 write_nic_byte(dev, SIFS_OFDM, val[2]);
4576                 // SIFS for OFDM consecutive tx like CTS data!
4577                 write_nic_byte(dev, SIFS_OFDM+1, val[3]);
4578         }
4579
4580         write_nic_dword(dev, INIRTSMCS_SEL, regRRSR);
4581         write_nic_byte(dev, BW_OPMODE, regBwOpMode);
4582
4583         //
4584         // Suggested by SD1 Alex, 2008-06-14.
4585         //
4586         //PlatformEFIOWrite1Byte(Adapter, TXOP_STALL_CTRL, 0x80);//NAV to protect all TXOP.
4587
4588         //
4589         // Set Data Auto Rate Fallback Retry Count register.
4590         //
4591         write_nic_dword(dev, DARFRC, 0x02010000);
4592         write_nic_dword(dev, DARFRC+4, 0x06050403);
4593         write_nic_dword(dev, RARFRC, 0x02010000);
4594         write_nic_dword(dev, RARFRC+4, 0x06050403);
4595
4596         // Set Data Auto Rate Fallback Reg. Added by Roger, 2008.09.22.
4597         for (i = 0; i < 8; i++)
4598                 write_nic_dword(dev, ARFR0+i*4, 0x1f0ffff0);
4599
4600         //
4601         // Aggregation length limit. Revised by Roger. 2008.09.22.
4602         //
4603         write_nic_byte(dev, AGGLEN_LMT_H, 0x0f);        // Set AMPDU length to 12Kbytes for ShortGI case.
4604         write_nic_dword(dev, AGGLEN_LMT_L, 0xddd77442); // Long GI
4605         write_nic_dword(dev, AGGLEN_LMT_L+4, 0xfffdd772);
4606
4607         // Set NAV protection length
4608         write_nic_word(dev, NAV_PROT_LEN, 0x0080);
4609
4610         // Set TXOP stall control for several queue/HI/BCN/MGT/
4611         write_nic_byte(dev, TXOP_STALL_CTRL, 0x00); // NAV Protect next packet.
4612
4613         // Set MSDU lifetime.
4614         write_nic_byte(dev, MLT, 0x8f);
4615
4616         // Set CCK/OFDM SIFS
4617         write_nic_word(dev, SIFS_CCK, 0x0a0a); // CCK SIFS shall always be 10us.
4618         write_nic_word(dev, SIFS_OFDM, 0x0e0e);
4619
4620         write_nic_byte(dev, ACK_TIMEOUT, 0x40);
4621
4622         // CF-END Threshold
4623         write_nic_byte(dev, CFEND_TH, 0xFF);
4624
4625         //
4626         // For Min Spacing configuration.
4627         //
4628         switch(priv->rf_type)
4629         {
4630                 case RF_1T2R:
4631                 case RF_1T1R:
4632                         RT_TRACE(COMP_INIT, "Initializeadapter: RF_Type%s\n", (priv->rf_type==RF_1T1R? "(1T1R)":"(1T2R)"));
4633                         priv->MinSpaceCfg = (MAX_MSS_DENSITY_1T<<3);
4634                         break;
4635                 case RF_2T2R:
4636                 case RF_2T2R_GREEN:
4637                         RT_TRACE(COMP_INIT, "Initializeadapter:RF_Type(2T2R)\n");
4638                         priv->MinSpaceCfg = (MAX_MSS_DENSITY_2T<<3);
4639                         break;
4640         }
4641         write_nic_byte(dev, AMPDU_MIN_SPACE, priv->MinSpaceCfg);
4642
4643         //LZM 090219
4644         //
4645         // For Min Spacing configuration.
4646         //
4647         //priv->MinSpaceCfg = 0x00;
4648         //rtl8192SU_SetHwRegAmpduMinSpace(dev, priv->MinSpaceCfg);
4649 }
4650
4651
4652 //      Description:    Initial HW relted registers.
4653 //
4654 //      Assumption:     This function is only invoked at driver intialization once.
4655 //
4656 //      2008.06.10, Added by Roger.
4657 bool rtl8192SU_adapter_start(struct net_device *dev)
4658 {
4659         struct r8192_priv *priv = ieee80211_priv(dev);
4660         //u32                                   dwRegRead = 0;
4661         //bool                                  init_status = true;
4662         //u32                                   ulRegRead;
4663         bool                                            rtStatus = true;
4664         //u8                                    PipeIndex;
4665         //u8                                    eRFPath, tmpU1b;
4666         u8 fw_download_times = 1;
4667
4668
4669         RT_TRACE(COMP_INIT, "--->InitializeAdapter8192SUsb()\n");
4670
4671         //pHalData->bGPIOChangeRF = FALSE;
4672
4673
4674         //
4675         // <Roger_Notes> 2008.06.15.
4676         //
4677         // Initialization Steps on RTL8192SU:
4678         // a. MAC initialization prior to sending down firmware code.
4679         // b. Download firmware code step by step(i.e., IMEM, EMEM, DMEM).
4680         // c. MAC configuration after firmware has been download successfully.
4681         // d. Initialize BB related configurations.
4682         // e. Initialize RF related configurations.
4683         // f.  Start to BulkIn transfer.
4684         //
4685
4686         //
4687         //a. MAC initialization prior to send down firmware code.
4688         //
4689 start:
4690         rtl8192SU_MacConfigBeforeFwDownloadASIC(dev);
4691
4692         //
4693         //b. Download firmware code step by step(i.e., IMEM, EMEM, DMEM).
4694         //
4695         rtStatus = FirmwareDownload92S(dev);
4696         if(rtStatus != true)
4697         {
4698                 if(fw_download_times == 1){
4699                         RT_TRACE(COMP_INIT, "InitializeAdapter8192SUsb(): Download Firmware failed once, Download again!!\n");
4700                         fw_download_times = fw_download_times + 1;
4701                         goto start;
4702                 }else{
4703                         RT_TRACE(COMP_INIT, "InitializeAdapter8192SUsb(): Download Firmware failed twice, end!!\n");
4704                 goto end;
4705         }
4706         }
4707         //
4708         //c. MAC configuration after firmware has been download successfully.
4709         //
4710         rtl8192SU_MacConfigAfterFwDownload(dev);
4711
4712         //priv->bLbusEnable = TRUE;
4713         //if(priv->RegRfOff == TRUE)
4714         //      priv->eRFPowerState = eRfOff;
4715
4716         // Save target channel
4717         // <Roger_Notes> Current Channel will be updated again later.
4718         //priv->CurrentChannel = Channel;
4719         rtStatus = PHY_MACConfig8192S(dev);//===>ok
4720         if(rtStatus != true)
4721         {
4722                 RT_TRACE(COMP_INIT, "InitializeAdapter8192SUsb(): Fail to configure MAC!!\n");
4723                 goto end;
4724         }
4725         if (1){
4726                 int i;
4727                 for (i=0; i<4; i++)
4728                         write_nic_dword(dev,WDCAPARA_ADD[i], 0x5e4322);
4729                 write_nic_byte(dev,AcmHwCtrl, 0x01);
4730         }
4731
4732
4733         //
4734         //d. Initialize BB related configurations.
4735         //
4736
4737         rtStatus = PHY_BBConfig8192S(dev);//===>ok
4738         if(rtStatus != true)
4739         {
4740                 RT_TRACE(COMP_INIT, "InitializeAdapter8192SUsb(): Fail to configure BB!!\n");
4741                 goto end;
4742         }
4743
4744         rtl8192_setBBreg(dev, rFPGA0_AnalogParameter2, 0xff, 0x58);//===>ok
4745
4746         //
4747         // e. Initialize RF related configurations.
4748         //
4749         // 2007/11/02 MH Before initalizing RF. We can not use FW to do RF-R/W.
4750         priv->Rf_Mode = RF_OP_By_SW_3wire;
4751
4752         // For RF test only from Scott's suggestion
4753         //write_nic_byte(dev, 0x27, 0xDB);
4754         //write_nic_byte(dev, 0x1B, 0x07);
4755
4756
4757         write_nic_byte(dev, AFE_XTAL_CTRL+1, 0xDB);
4758
4759         // <Roger_Notes> The following IOs are configured for each RF modules.
4760         // Enable RF module and reset RF and SDM module. 2008.11.17.
4761         if(priv->card_8192_version == VERSION_8192S_ACUT)
4762                 write_nic_byte(dev, SPS1_CTRL+3, (u8)(RF_EN|RF_RSTB|RF_SDMRSTB)); // Fix A-Cut bug.
4763         else
4764                 write_nic_byte(dev, RF_CTRL, (u8)(RF_EN|RF_RSTB|RF_SDMRSTB));
4765
4766         rtStatus = PHY_RFConfig8192S(dev);//===>ok
4767         if(rtStatus != true)
4768         {
4769                 RT_TRACE(COMP_INIT, "InitializeAdapter8192SUsb(): Fail to configure RF!!\n");
4770                 goto end;
4771         }
4772
4773
4774         // Set CCK and OFDM Block "ON"
4775         rtl8192_setBBreg(dev, rFPGA0_RFMOD, bCCKEn, 0x1);
4776         rtl8192_setBBreg(dev, rFPGA0_RFMOD, bOFDMEn, 0x1);
4777
4778         //
4779         // Turn off Radio B while RF type is 1T1R by SD3 Wilsion's request.
4780         // Revised by Roger, 2008.12.18.
4781         //
4782         if(priv->rf_type == RF_1T1R)
4783         {
4784                 // This is needed for PHY_REG after 20081219
4785                 rtl8192_setBBreg(dev, rFPGA0_RFMOD, 0xff000000, 0x03);
4786                 // This is needed for PHY_REG before 20081219
4787                 //PHY_SetBBReg(Adapter, rOFDM0_TRxPathEnable, bMaskByte0, 0x11);
4788         }
4789
4790
4791         //LZM 090219
4792         // Set CCK and OFDM Block "ON"
4793         //rtl8192_setBBreg(dev, rFPGA0_RFMOD, bCCKEn, 0x1);
4794         //rtl8192_setBBreg(dev, rFPGA0_RFMOD, bOFDMEn, 0x1);
4795
4796
4797         //3//Get hardware version, do it in read eeprom?
4798         //GetHardwareVersion819xUsb(Adapter);
4799
4800         //3//
4801         //3 //Set Hardware
4802         //3//
4803         rtl8192SU_HwConfigureRTL8192SUsb(dev);//==>ok
4804
4805         //
4806         // <Roger_Notes> We set MAC address here if autoload was failed before,
4807         // otherwise IDR0 will NOT contain any value.
4808         //
4809         write_nic_dword(dev, IDR0, ((u32*)dev->dev_addr)[0]);
4810         write_nic_word(dev, IDR4, ((u16*)(dev->dev_addr + 4))[0]);
4811         if(!priv->bInHctTest)
4812         {
4813                 if(priv->ResetProgress == RESET_TYPE_NORESET)
4814                 {
4815                         //RT_TRACE(COMP_MLME, DBG_LOUD, ("Initializeadapter8192SUsb():RegWirelessMode(%#x) \n", Adapter->RegWirelessMode));
4816                         //Adapter->HalFunc.SetWirelessModeHandler(Adapter, Adapter->RegWirelessMode);
4817                         rtl8192_SetWirelessMode(dev, priv->ieee80211->mode);//===>ok
4818                 }
4819         }
4820         else
4821         {
4822                 priv->ieee80211->mode = WIRELESS_MODE_G;
4823                 rtl8192_SetWirelessMode(dev, WIRELESS_MODE_G);
4824         }
4825
4826         //Security related.
4827         //-----------------------------------------------------------------------------
4828         // Set up security related. 070106, by rcnjko:
4829         // 1. Clear all H/W keys.
4830         // 2. Enable H/W encryption/decryption.
4831         //-----------------------------------------------------------------------------
4832         //CamResetAllEntry(Adapter);
4833         //Adapter->HalFunc.EnableHWSecCfgHandler(Adapter);
4834
4835         //SecClearAllKeys(Adapter);
4836         CamResetAllEntry(dev);
4837         //SecInit(Adapter);
4838         {
4839                 u8 SECR_value = 0x0;
4840                 SECR_value |= SCR_TxEncEnable;
4841                 SECR_value |= SCR_RxDecEnable;
4842                 SECR_value |= SCR_NoSKMC;
4843                 write_nic_byte(dev, SECR, SECR_value);
4844         }
4845
4846 #ifdef TO_DO_LIST
4847
4848         //PHY_UpdateInitialGain(dev);
4849
4850         if(priv->RegRfOff == true)
4851         { // User disable RF via registry.
4852                 u8 eRFPath = 0;
4853
4854                 RT_TRACE((COMP_INIT|COMP_RF), "InitializeAdapter8192SUsb(): Turn off RF for RegRfOff ----------\n");
4855                 MgntActSet_RF_State(dev, eRfOff, RF_CHANGE_BY_SW);
4856                 // Those action will be discard in MgntActSet_RF_State because off the same state
4857                 for(eRFPath = 0; eRFPath <priv->NumTotalRFPath; eRFPath++)
4858                         rtl8192_setBBreg(dev, (RF90_RADIO_PATH_E)eRFPath, 0x4, 0xC00, 0x0);
4859         }
4860         else if(priv->RfOffReason > RF_CHANGE_BY_PS)
4861         { // H/W or S/W RF OFF before sleep.
4862                 RT_TRACE((COMP_INIT|COMP_RF), "InitializeAdapter8192SUsb(): Turn off RF for RfOffReason(%d) ----------\n", priv->RfOffReason);
4863                 MgntActSet_RF_State(dev, eRfOff, priv->RfOffReason);
4864         }
4865         else
4866         {
4867                 priv->eRFPowerState = eRfOn;
4868                 priv->RfOffReason = 0;
4869                 RT_TRACE((COMP_INIT|COMP_RF), "InitializeAdapter8192SUsb(): RF is on ----------\n");
4870         }
4871
4872 #endif
4873
4874
4875 //
4876 // f. Start to BulkIn transfer.
4877 //
4878 #ifdef TO_DO_LIST
4879
4880 #ifndef UNDER_VISTA
4881         {
4882                 u8      i;
4883                 PlatformAcquireSpinLock(Adapter, RT_RX_SPINLOCK);
4884
4885                 for(PipeIndex=0; PipeIndex < MAX_RX_QUEUE; PipeIndex++)
4886                 {
4887                         if (PipeIndex == 0)
4888                         {
4889                                 for(i=0; i<32; i++)
4890                                 HalUsbInMpdu(Adapter, PipeIndex);
4891                         }
4892                         else
4893                         {
4894                                 //HalUsbInMpdu(Adapter, PipeIndex);
4895                                 //HalUsbInMpdu(Adapter, PipeIndex);
4896                                 //HalUsbInMpdu(Adapter, PipeIndex);
4897                         }
4898                 }
4899                 PlatformReleaseSpinLock(Adapter, RT_RX_SPINLOCK);
4900         }
4901 #else
4902                 // Joseph add to 819X code base for Vista USB platform.
4903                 // This part may need to be add to Hal819xU code base. too.
4904                 PlatformUsbEnableInPipes(Adapter);
4905 #endif
4906
4907         RT_TRACE(COMP_INIT, "HighestOperaRate = %x\n", Adapter->MgntInfo.HighestOperaRate);
4908
4909         PlatformStartWorkItem( &(pHalData->RtUsbCheckForHangWorkItem) );
4910
4911         //
4912         // <Roger_EXP> The following  configurations are for ASIC verification temporally.
4913         // 2008.07.10.
4914         //
4915
4916 #endif
4917
4918         //
4919         // Read EEPROM TX power index and PHY_REG_PG.txt to capture correct
4920         // TX power index for different rate set.
4921         //
4922         //if(priv->card_8192_version >= VERSION_8192S_ACUT)
4923         {
4924                 // Get original hw reg values
4925                 PHY_GetHWRegOriginalValue(dev);
4926
4927                 // Write correct tx power index//FIXLZM
4928                 PHY_SetTxPowerLevel8192S(dev, priv->chan);
4929         }
4930
4931         {
4932         u8  tmpU1b = 0;
4933         // EEPROM R/W workaround
4934         tmpU1b = read_nic_byte(dev, MAC_PINMUX_CFG);
4935         write_nic_byte(dev, MAC_PINMUX_CFG, tmpU1b&(~GPIOMUX_EN));
4936         }
4937
4938 //
4939 //<Roger_Notes> 2008.08.19.
4940 // We return status here for temporal FPGA verification, 2008.08.19.
4941
4942 #ifdef RTL8192SU_FW_IQK
4943         write_nic_dword(dev, WFM5, FW_IQK_ENABLE);
4944         ChkFwCmdIoDone(dev);
4945 #endif
4946
4947         //
4948         // <Roger_Notes> We enable high power mechanism after NIC initialized.
4949         // 2008.11.27.
4950         //
4951         write_nic_dword(dev, WFM5, FW_RA_RESET);
4952         ChkFwCmdIoDone(dev);
4953         write_nic_dword(dev, WFM5, FW_RA_ACTIVE);
4954         ChkFwCmdIoDone(dev);
4955         write_nic_dword(dev, WFM5, FW_RA_REFRESH);
4956         ChkFwCmdIoDone(dev);
4957         write_nic_dword(dev, WFM5, FW_BB_RESET_ENABLE);
4958
4959 // <Roger_Notes> We return status here for temporal FPGA verification. 2008.05.12.
4960 //
4961
4962 end:
4963 return rtStatus;
4964 }
4965
4966 /***************************************************************************
4967     -------------------------------NET STUFF---------------------------
4968 ***************************************************************************/
4969
4970 static struct net_device_stats *rtl8192_stats(struct net_device *dev)
4971 {
4972         struct r8192_priv *priv = ieee80211_priv(dev);
4973
4974         return &priv->ieee80211->stats;
4975 }
4976
4977 bool
4978 HalTxCheckStuck819xUsb(
4979         struct net_device *dev
4980         )
4981 {
4982         struct r8192_priv *priv = ieee80211_priv(dev);
4983         u16             RegTxCounter = read_nic_word(dev, 0x128);
4984         bool            bStuck = FALSE;
4985         RT_TRACE(COMP_RESET,"%s():RegTxCounter is %d,TxCounter is %d\n",__FUNCTION__,RegTxCounter,priv->TxCounter);
4986         if(priv->TxCounter==RegTxCounter)
4987                 bStuck = TRUE;
4988
4989         priv->TxCounter = RegTxCounter;
4990
4991         return bStuck;
4992 }
4993
4994 /*
4995 *       <Assumption: RT_TX_SPINLOCK is acquired.>
4996 *       First added: 2006.11.19 by emily
4997 */
4998 RESET_TYPE
4999 TxCheckStuck(struct net_device *dev)
5000 {
5001         struct r8192_priv *priv = ieee80211_priv(dev);
5002         u8                      QueueID;
5003 //      PRT_TCB                 pTcb;
5004 //      u8                      ResetThreshold;
5005         bool                    bCheckFwTxCnt = false;
5006         //unsigned long flags;
5007
5008         //
5009         // Decide Stuch threshold according to current power save mode
5010         //
5011
5012 //     RT_TRACE(COMP_RESET, " ==> TxCheckStuck()\n");
5013 //           PlatformAcquireSpinLock(Adapter, RT_TX_SPINLOCK);
5014 //           spin_lock_irqsave(&priv->ieee80211->lock,flags);
5015              for (QueueID = 0; QueueID<=BEACON_QUEUE;QueueID ++)
5016              {
5017                         if(QueueID == TXCMD_QUEUE)
5018                          continue;
5019 #if 1
5020                         if((skb_queue_len(&priv->ieee80211->skb_waitQ[QueueID]) == 0)  && (skb_queue_len(&priv->ieee80211->skb_aggQ[QueueID]) == 0))
5021                                 continue;
5022 #endif
5023
5024                      bCheckFwTxCnt = true;
5025              }
5026 //           PlatformReleaseSpinLock(Adapter, RT_TX_SPINLOCK);
5027 //      spin_unlock_irqrestore(&priv->ieee80211->lock,flags);
5028 //      RT_TRACE(COMP_RESET,"bCheckFwTxCnt is %d\n",bCheckFwTxCnt);
5029 #if 1
5030         if(bCheckFwTxCnt)
5031         {
5032                 if(HalTxCheckStuck819xUsb(dev))
5033                 {
5034                         RT_TRACE(COMP_RESET, "TxCheckStuck(): Fw indicates no Tx condition! \n");
5035                         return RESET_TYPE_SILENT;
5036                 }
5037         }
5038 #endif
5039         return RESET_TYPE_NORESET;
5040 }
5041
5042 bool
5043 HalRxCheckStuck819xUsb(struct net_device *dev)
5044 {
5045         u16     RegRxCounter = read_nic_word(dev, 0x130);
5046         struct r8192_priv *priv = ieee80211_priv(dev);
5047         bool bStuck = FALSE;
5048 //#ifdef RTL8192SU
5049
5050 //#else
5051         static u8       rx_chk_cnt = 0;
5052         RT_TRACE(COMP_RESET,"%s(): RegRxCounter is %d,RxCounter is %d\n",__FUNCTION__,RegRxCounter,priv->RxCounter);
5053         // If rssi is small, we should check rx for long time because of bad rx.
5054         // or maybe it will continuous silent reset every 2 seconds.
5055         rx_chk_cnt++;
5056         if(priv->undecorated_smoothed_pwdb >= (RateAdaptiveTH_High+5))
5057         {
5058                 rx_chk_cnt = 0; //high rssi, check rx stuck right now.
5059         }
5060         else if(priv->undecorated_smoothed_pwdb < (RateAdaptiveTH_High+5) &&
5061                 ((priv->CurrentChannelBW!=HT_CHANNEL_WIDTH_20&&priv->undecorated_smoothed_pwdb>=RateAdaptiveTH_Low_40M) ||
5062                 (priv->CurrentChannelBW==HT_CHANNEL_WIDTH_20&&priv->undecorated_smoothed_pwdb>=RateAdaptiveTH_Low_20M)) )
5063         {
5064                 if(rx_chk_cnt < 2)
5065                 {
5066                         return bStuck;
5067                 }
5068                 else
5069                 {
5070                         rx_chk_cnt = 0;
5071                 }
5072         }
5073         else if(((priv->CurrentChannelBW!=HT_CHANNEL_WIDTH_20&&priv->undecorated_smoothed_pwdb<RateAdaptiveTH_Low_40M) ||
5074                 (priv->CurrentChannelBW==HT_CHANNEL_WIDTH_20&&priv->undecorated_smoothed_pwdb<RateAdaptiveTH_Low_20M)) &&
5075                 priv->undecorated_smoothed_pwdb >= VeryLowRSSI)
5076         {
5077                 if(rx_chk_cnt < 4)
5078                 {
5079                         //DbgPrint("RSSI < %d && RSSI >= %d, no check this time \n", RateAdaptiveTH_Low, VeryLowRSSI);
5080                         return bStuck;
5081                 }
5082                 else
5083                 {
5084                         rx_chk_cnt = 0;
5085                         //DbgPrint("RSSI < %d && RSSI >= %d, check this time \n", RateAdaptiveTH_Low, VeryLowRSSI);
5086                 }
5087         }
5088         else
5089         {
5090                 if(rx_chk_cnt < 8)
5091                 {
5092                         //DbgPrint("RSSI <= %d, no check this time \n", VeryLowRSSI);
5093                         return bStuck;
5094                 }
5095                 else
5096                 {
5097                         rx_chk_cnt = 0;
5098                         //DbgPrint("RSSI <= %d, check this time \n", VeryLowRSSI);
5099                 }
5100         }
5101 //#endif
5102
5103         if(priv->RxCounter==RegRxCounter)
5104                 bStuck = TRUE;
5105
5106         priv->RxCounter = RegRxCounter;
5107
5108         return bStuck;
5109 }
5110
5111 RESET_TYPE
5112 RxCheckStuck(struct net_device *dev)
5113 {
5114         struct r8192_priv *priv = ieee80211_priv(dev);
5115         //int                     i;
5116         bool        bRxCheck = FALSE;
5117
5118 //       RT_TRACE(COMP_RESET," ==> RxCheckStuck()\n");
5119         //PlatformAcquireSpinLock(Adapter, RT_RX_SPINLOCK);
5120
5121          if(priv->IrpPendingCount > 1)
5122                 bRxCheck = TRUE;
5123        //PlatformReleaseSpinLock(Adapter, RT_RX_SPINLOCK);
5124
5125 //       RT_TRACE(COMP_RESET,"bRxCheck is %d \n",bRxCheck);
5126         if(bRxCheck)
5127         {
5128                 if(HalRxCheckStuck819xUsb(dev))
5129                 {
5130                         RT_TRACE(COMP_RESET, "RxStuck Condition\n");
5131                         return RESET_TYPE_SILENT;
5132                 }
5133         }
5134         return RESET_TYPE_NORESET;
5135 }
5136
5137
5138 /**
5139 *       This function is called by Checkforhang to check whether we should ask OS to reset driver
5140 *
5141 *       \param pAdapter The adapter context for this miniport
5142 *
5143 *       Note:NIC with USB interface sholud not call this function because we cannot scan descriptor
5144 *       to judge whether there is tx stuck.
5145 *       Note: This function may be required to be rewrite for Vista OS.
5146 *       <<<Assumption: Tx spinlock has been acquired >>>
5147 *
5148 *       8185 and 8185b does not implement this function. This is added by Emily at 2006.11.24
5149 */
5150 RESET_TYPE
5151 rtl819x_ifcheck_resetornot(struct net_device *dev)
5152 {
5153         struct r8192_priv *priv = ieee80211_priv(dev);
5154         RESET_TYPE      TxResetType = RESET_TYPE_NORESET;
5155         RESET_TYPE      RxResetType = RESET_TYPE_NORESET;
5156         RT_RF_POWER_STATE       rfState;
5157
5158         return RESET_TYPE_NORESET;
5159
5160         rfState = priv->ieee80211->eRFPowerState;
5161
5162         TxResetType = TxCheckStuck(dev);
5163 #if 1
5164         if( rfState != eRfOff ||
5165                 /*ADAPTER_TEST_STATUS_FLAG(Adapter, ADAPTER_STATUS_FW_DOWNLOAD_FAILURE)) &&*/
5166                 (priv->ieee80211->iw_mode != IW_MODE_ADHOC))
5167         {
5168                 // If driver is in the status of firmware download failure , driver skips RF initialization and RF is
5169                 // in turned off state. Driver should check whether Rx stuck and do silent reset. And
5170                 // if driver is in firmware download failure status, driver should initialize RF in the following
5171                 // silent reset procedure Emily, 2008.01.21
5172
5173                 // Driver should not check RX stuck in IBSS mode because it is required to
5174                 // set Check BSSID in order to send beacon, however, if check BSSID is
5175                 // set, STA cannot hear any packet a all. Emily, 2008.04.12
5176                 RxResetType = RxCheckStuck(dev);
5177         }
5178 #endif
5179         if(TxResetType==RESET_TYPE_NORMAL || RxResetType==RESET_TYPE_NORMAL)
5180                 return RESET_TYPE_NORMAL;
5181         else if(TxResetType==RESET_TYPE_SILENT || RxResetType==RESET_TYPE_SILENT){
5182                 RT_TRACE(COMP_RESET,"%s():silent reset\n",__FUNCTION__);
5183                 return RESET_TYPE_SILENT;
5184         }
5185         else
5186                 return RESET_TYPE_NORESET;
5187
5188 }
5189
5190 void rtl8192_cancel_deferred_work(struct r8192_priv* priv);
5191 int _rtl8192_up(struct net_device *dev);
5192 int rtl8192_close(struct net_device *dev);
5193
5194
5195
5196 void
5197 CamRestoreAllEntry(     struct net_device *dev)
5198 {
5199         u8 EntryId = 0;
5200         struct r8192_priv *priv = ieee80211_priv(dev);
5201         u8*     MacAddr = priv->ieee80211->current_network.bssid;
5202
5203         static u8       CAM_CONST_ADDR[4][6] = {
5204                 {0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
5205                 {0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
5206                 {0x00, 0x00, 0x00, 0x00, 0x00, 0x02},
5207                 {0x00, 0x00, 0x00, 0x00, 0x00, 0x03}};
5208         static u8       CAM_CONST_BROAD[] =
5209                 {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
5210
5211         RT_TRACE(COMP_SEC, "CamRestoreAllEntry: \n");
5212
5213
5214         if ((priv->ieee80211->pairwise_key_type == KEY_TYPE_WEP40)||
5215             (priv->ieee80211->pairwise_key_type == KEY_TYPE_WEP104))
5216         {
5217
5218                 for(EntryId=0; EntryId<4; EntryId++)
5219                 {
5220                         {
5221                                 MacAddr = CAM_CONST_ADDR[EntryId];
5222                                 setKey(dev,
5223                                                 EntryId ,
5224                                                 EntryId,
5225                                                 priv->ieee80211->pairwise_key_type,
5226                                                 MacAddr,
5227                                                 0,
5228                                                 NULL);
5229                         }
5230                 }
5231
5232         }
5233         else if(priv->ieee80211->pairwise_key_type == KEY_TYPE_TKIP)
5234         {
5235
5236                 {
5237                         if(priv->ieee80211->iw_mode == IW_MODE_ADHOC)
5238                                 setKey(dev,
5239                                                 4,
5240                                                 0,
5241                                                 priv->ieee80211->pairwise_key_type,
5242                                                 (u8*)dev->dev_addr,
5243                                                 0,
5244                                                 NULL);
5245                         else
5246                                 setKey(dev,
5247                                                 4,
5248                                                 0,
5249                                                 priv->ieee80211->pairwise_key_type,
5250                                                 MacAddr,
5251                                                 0,
5252                                                 NULL);
5253                 }
5254         }
5255         else if(priv->ieee80211->pairwise_key_type == KEY_TYPE_CCMP)
5256         {
5257
5258                 {
5259                         if(priv->ieee80211->iw_mode == IW_MODE_ADHOC)
5260                                 setKey(dev,
5261                                                 4,
5262                                                 0,
5263                                                 priv->ieee80211->pairwise_key_type,
5264                                                 (u8*)dev->dev_addr,
5265                                                 0,
5266                                                 NULL);
5267                         else
5268                                 setKey(dev,
5269                                                 4,
5270                                                 0,
5271                                                 priv->ieee80211->pairwise_key_type,
5272                                                 MacAddr,
5273                                                 0,
5274                                                 NULL);
5275                 }
5276         }
5277
5278
5279
5280         if(priv->ieee80211->group_key_type == KEY_TYPE_TKIP)
5281         {
5282                 MacAddr = CAM_CONST_BROAD;
5283                 for(EntryId=1 ; EntryId<4 ; EntryId++)
5284                 {
5285                         {
5286                                 setKey(dev,
5287                                                 EntryId,
5288                                                 EntryId,
5289                                                 priv->ieee80211->group_key_type,
5290                                                 MacAddr,
5291                                                 0,
5292                                                 NULL);
5293                         }
5294                 }
5295                 if(priv->ieee80211->iw_mode == IW_MODE_ADHOC)
5296                                 setKey(dev,
5297                                                 0,
5298                                                 0,
5299                                                 priv->ieee80211->group_key_type,
5300                                                 CAM_CONST_ADDR[0],
5301                                                 0,
5302                                                 NULL);
5303         }
5304         else if(priv->ieee80211->group_key_type == KEY_TYPE_CCMP)
5305         {
5306                 MacAddr = CAM_CONST_BROAD;
5307                 for(EntryId=1; EntryId<4 ; EntryId++)
5308                 {
5309                         {
5310                                 setKey(dev,
5311                                                 EntryId ,
5312                                                 EntryId,
5313                                                 priv->ieee80211->group_key_type,
5314                                                 MacAddr,
5315                                                 0,
5316                                                 NULL);
5317                         }
5318                 }
5319
5320                 if(priv->ieee80211->iw_mode == IW_MODE_ADHOC)
5321                                 setKey(dev,
5322                                                 0 ,
5323                                                 0,
5324                                                 priv->ieee80211->group_key_type,
5325                                                 CAM_CONST_ADDR[0],
5326                                                 0,
5327                                                 NULL);
5328         }
5329 }
5330 //////////////////////////////////////////////////////////////
5331 // This function is used to fix Tx/Rx stop bug temporarily.
5332 // This function will do "system reset" to NIC when Tx or Rx is stuck.
5333 // The method checking Tx/Rx stuck of this function is supported by FW,
5334 // which reports Tx and Rx counter to register 0x128 and 0x130.
5335 //////////////////////////////////////////////////////////////
5336 void
5337 rtl819x_ifsilentreset(struct net_device *dev)
5338 {
5339         //OCTET_STRING asocpdu;
5340         struct r8192_priv *priv = ieee80211_priv(dev);
5341         u8      reset_times = 0;
5342         int reset_status = 0;
5343         struct ieee80211_device *ieee = priv->ieee80211;
5344
5345
5346         // 2007.07.20. If we need to check CCK stop, please uncomment this line.
5347         //bStuck = Adapter->HalFunc.CheckHWStopHandler(Adapter);
5348
5349         if(priv->ResetProgress==RESET_TYPE_NORESET)
5350         {
5351 RESET_START:
5352
5353                 RT_TRACE(COMP_RESET,"=========>Reset progress!! \n");
5354
5355                 // Set the variable for reset.
5356                 priv->ResetProgress = RESET_TYPE_SILENT;
5357 //              rtl8192_close(dev);
5358 #if 1
5359                 down(&priv->wx_sem);
5360                 if(priv->up == 0)
5361                 {
5362                         RT_TRACE(COMP_ERR,"%s():the driver is not up! return\n",__FUNCTION__);
5363                         up(&priv->wx_sem);
5364                         return ;
5365                 }
5366                 priv->up = 0;
5367                 RT_TRACE(COMP_RESET,"%s():======>start to down the driver\n",__FUNCTION__);
5368 //              if(!netif_queue_stopped(dev))
5369 //                      netif_stop_queue(dev);
5370
5371                 rtl8192_rtx_disable(dev);
5372                 rtl8192_cancel_deferred_work(priv);
5373                 deinit_hal_dm(dev);
5374                 del_timer_sync(&priv->watch_dog_timer);
5375
5376                 ieee->sync_scan_hurryup = 1;
5377                 if(ieee->state == IEEE80211_LINKED)
5378                 {
5379                         down(&ieee->wx_sem);
5380                         printk("ieee->state is IEEE80211_LINKED\n");
5381                         ieee80211_stop_send_beacons(priv->ieee80211);
5382                         del_timer_sync(&ieee->associate_timer);
5383                         cancel_delayed_work(&ieee->associate_retry_wq);
5384                         ieee80211_stop_scan(ieee);
5385                         netif_carrier_off(dev);
5386                         up(&ieee->wx_sem);
5387                 }
5388                 else{
5389                         printk("ieee->state is NOT LINKED\n");
5390                         ieee80211_softmac_stop_protocol(priv->ieee80211);                       }
5391                 up(&priv->wx_sem);
5392                 RT_TRACE(COMP_RESET,"%s():<==========down process is finished\n",__FUNCTION__);
5393         //rtl8192_irq_disable(dev);
5394                 RT_TRACE(COMP_RESET,"%s():===========>start to up the driver\n",__FUNCTION__);
5395                 reset_status = _rtl8192_up(dev);
5396
5397                 RT_TRACE(COMP_RESET,"%s():<===========up process is finished\n",__FUNCTION__);
5398                 if(reset_status == -EAGAIN)
5399                 {
5400                         if(reset_times < 3)
5401                         {
5402                                 reset_times++;
5403                                 goto RESET_START;
5404                         }
5405                         else
5406                         {
5407                                 RT_TRACE(COMP_ERR," ERR!!! %s():  Reset Failed!!\n", __FUNCTION__);
5408                         }
5409                 }
5410 #endif
5411                 ieee->is_silent_reset = 1;
5412 #if 1
5413                 EnableHWSecurityConfig8192(dev);
5414 #if 1
5415                 if(ieee->state == IEEE80211_LINKED && ieee->iw_mode == IW_MODE_INFRA)
5416                 {
5417                         ieee->set_chan(ieee->dev, ieee->current_network.channel);
5418
5419 #if 1
5420                         queue_work(ieee->wq, &ieee->associate_complete_wq);
5421 #endif
5422
5423                 }
5424                 else if(ieee->state == IEEE80211_LINKED && ieee->iw_mode == IW_MODE_ADHOC)
5425                 {
5426                         ieee->set_chan(ieee->dev, ieee->current_network.channel);
5427                         ieee->link_change(ieee->dev);
5428
5429                 //      notify_wx_assoc_event(ieee);
5430
5431                         ieee80211_start_send_beacons(ieee);
5432
5433                         if (ieee->data_hard_resume)
5434                                 ieee->data_hard_resume(ieee->dev);
5435                         netif_carrier_on(ieee->dev);
5436                 }
5437 #endif
5438
5439                 CamRestoreAllEntry(dev);
5440
5441                 priv->ResetProgress = RESET_TYPE_NORESET;
5442                 priv->reset_count++;
5443
5444                 priv->bForcedSilentReset =false;
5445                 priv->bResetInProgress = false;
5446
5447                 // For test --> force write UFWP.
5448                 write_nic_byte(dev, UFWP, 1);
5449                 RT_TRACE(COMP_RESET, "Reset finished!! ====>[%d]\n", priv->reset_count);
5450 #endif
5451         }
5452 }
5453
5454 void CAM_read_entry(
5455         struct net_device *dev,
5456         u32                     iIndex
5457 )
5458 {
5459         u32 target_command=0;
5460          u32 target_content=0;
5461          u8 entry_i=0;
5462          u32 ulStatus;
5463         s32 i=100;
5464 //      printk("=======>start read CAM\n");
5465         for(entry_i=0;entry_i<CAM_CONTENT_COUNT;entry_i++)
5466         {
5467         // polling bit, and No Write enable, and address
5468                 target_command= entry_i+CAM_CONTENT_COUNT*iIndex;
5469                 target_command= target_command | BIT31;
5470
5471         //Check polling bit is clear
5472 //      mdelay(1);
5473 #if 1
5474                 while((i--)>=0)
5475                 {
5476                         ulStatus = read_nic_dword(dev, RWCAM);
5477                         if(ulStatus & BIT31){
5478                                 continue;
5479                         }
5480                         else{
5481                                 break;
5482                         }
5483                 }
5484 #endif
5485                 write_nic_dword(dev, RWCAM, target_command);
5486                 RT_TRACE(COMP_SEC,"CAM_read_entry(): WRITE A0: %x \n",target_command);
5487          //     printk("CAM_read_entry(): WRITE A0: %lx \n",target_command);
5488                 target_content = read_nic_dword(dev, RCAMO);
5489                 RT_TRACE(COMP_SEC, "CAM_read_entry(): WRITE A8: %x \n",target_content);
5490          //     printk("CAM_read_entry(): WRITE A8: %lx \n",target_content);
5491         }
5492         printk("\n");
5493 }
5494
5495 void rtl819x_update_rxcounts(
5496         struct r8192_priv *priv,
5497         u32* TotalRxBcnNum,
5498         u32* TotalRxDataNum
5499 )
5500 {
5501         u16                     SlotIndex;
5502         u8                      i;
5503
5504         *TotalRxBcnNum = 0;
5505         *TotalRxDataNum = 0;
5506
5507         SlotIndex = (priv->ieee80211->LinkDetectInfo.SlotIndex++)%(priv->ieee80211->LinkDetectInfo.SlotNum);
5508         priv->ieee80211->LinkDetectInfo.RxBcnNum[SlotIndex] = priv->ieee80211->LinkDetectInfo.NumRecvBcnInPeriod;
5509         priv->ieee80211->LinkDetectInfo.RxDataNum[SlotIndex] = priv->ieee80211->LinkDetectInfo.NumRecvDataInPeriod;
5510         for( i=0; i<priv->ieee80211->LinkDetectInfo.SlotNum; i++ ){
5511                 *TotalRxBcnNum += priv->ieee80211->LinkDetectInfo.RxBcnNum[i];
5512                 *TotalRxDataNum += priv->ieee80211->LinkDetectInfo.RxDataNum[i];
5513         }
5514 }
5515
5516 extern  void    rtl819x_watchdog_wqcallback(struct work_struct *work)
5517 {
5518         struct delayed_work *dwork = container_of(work,struct delayed_work,work);
5519        struct r8192_priv *priv = container_of(dwork,struct r8192_priv,watch_dog_wq);
5520        struct net_device *dev = priv->ieee80211->dev;
5521         struct ieee80211_device* ieee = priv->ieee80211;
5522         RESET_TYPE      ResetType = RESET_TYPE_NORESET;
5523         static u8       check_reset_cnt=0;
5524         bool bBusyTraffic = false;
5525
5526         if(!priv->up)
5527                 return;
5528         hal_dm_watchdog(dev);
5529
5530         {//to get busy traffic condition
5531                 if(ieee->state == IEEE80211_LINKED)
5532                 {
5533                         //windows mod 666 to 100.
5534                         //if(   ieee->LinkDetectInfo.NumRxOkInPeriod> 666 ||
5535                         //      ieee->LinkDetectInfo.NumTxOkInPeriod> 666 ) {
5536                         if(     ieee->LinkDetectInfo.NumRxOkInPeriod> 100 ||
5537                                 ieee->LinkDetectInfo.NumTxOkInPeriod> 100 ) {
5538                                 bBusyTraffic = true;
5539                         }
5540                         ieee->LinkDetectInfo.NumRxOkInPeriod = 0;
5541                         ieee->LinkDetectInfo.NumTxOkInPeriod = 0;
5542                         ieee->LinkDetectInfo.bBusyTraffic = bBusyTraffic;
5543                 }
5544         }
5545         //added by amy for AP roaming
5546         {
5547                 if(priv->ieee80211->state == IEEE80211_LINKED && priv->ieee80211->iw_mode == IW_MODE_INFRA)
5548                 {
5549                         u32     TotalRxBcnNum = 0;
5550                         u32     TotalRxDataNum = 0;
5551
5552                         rtl819x_update_rxcounts(priv, &TotalRxBcnNum, &TotalRxDataNum);
5553                         if((TotalRxBcnNum+TotalRxDataNum) == 0)
5554                         {
5555                                 #ifdef TODO
5556                                 if(rfState == eRfOff)
5557                                         RT_TRACE(COMP_ERR,"========>%s()\n",__FUNCTION__);
5558                                 #endif
5559                                 printk("===>%s(): AP is power off,connect another one\n",__FUNCTION__);
5560                         //      Dot11d_Reset(dev);
5561                                 priv->ieee80211->state = IEEE80211_ASSOCIATING;
5562                                 notify_wx_assoc_event(priv->ieee80211);
5563                                 RemovePeerTS(priv->ieee80211,priv->ieee80211->current_network.bssid);
5564                                 ieee->is_roaming = true;
5565                                 priv->ieee80211->link_change(dev);
5566                                 queue_work(priv->ieee80211->wq, &priv->ieee80211->associate_procedure_wq);
5567                         }
5568                 }
5569                 priv->ieee80211->LinkDetectInfo.NumRecvBcnInPeriod=0;
5570                 priv->ieee80211->LinkDetectInfo.NumRecvDataInPeriod=0;
5571         }
5572 //      CAM_read_entry(dev,4);
5573         //check if reset the driver
5574         if(check_reset_cnt++ >= 3 && !ieee->is_roaming)
5575         {
5576                 ResetType = rtl819x_ifcheck_resetornot(dev);
5577                 check_reset_cnt = 3;
5578                 //DbgPrint("Start to check silent reset\n");
5579         }
5580         //      RT_TRACE(COMP_RESET,"%s():priv->force_reset is %d,priv->ResetProgress is %d, priv->bForcedSilentReset is %d,priv->bDisableNormalResetCheck is %d,ResetType is %d\n",__FUNCTION__,priv->force_reset,priv->ResetProgress,priv->bForcedSilentReset,priv->bDisableNormalResetCheck,ResetType);
5581 #if 1
5582         if( (priv->force_reset) || (priv->ResetProgress==RESET_TYPE_NORESET &&
5583                 (priv->bForcedSilentReset ||
5584                 (!priv->bDisableNormalResetCheck && ResetType==RESET_TYPE_SILENT)))) // This is control by OID set in Pomelo
5585         {
5586                 RT_TRACE(COMP_RESET,"%s():priv->force_reset is %d,priv->ResetProgress is %d, priv->bForcedSilentReset is %d,priv->bDisableNormalResetCheck is %d,ResetType is %d\n",__FUNCTION__,priv->force_reset,priv->ResetProgress,priv->bForcedSilentReset,priv->bDisableNormalResetCheck,ResetType);
5587                 rtl819x_ifsilentreset(dev);
5588         }
5589 #endif
5590         priv->force_reset = false;
5591         priv->bForcedSilentReset = false;
5592         priv->bResetInProgress = false;
5593         RT_TRACE(COMP_TRACE, " <==RtUsbCheckForHangWorkItemCallback()\n");
5594
5595 }
5596
5597 void watch_dog_timer_callback(unsigned long data)
5598 {
5599         struct r8192_priv *priv = ieee80211_priv((struct net_device *) data);
5600         //printk("===============>watch_dog  timer\n");
5601         queue_delayed_work(priv->priv_wq,&priv->watch_dog_wq, 0);
5602         mod_timer(&priv->watch_dog_timer, jiffies + MSECS(IEEE80211_WATCH_DOG_TIME));
5603 }
5604 int _rtl8192_up(struct net_device *dev)
5605 {
5606         struct r8192_priv *priv = ieee80211_priv(dev);
5607         //int i;
5608         int init_status = 0;
5609         priv->up=1;
5610         priv->ieee80211->ieee_up=1;
5611         RT_TRACE(COMP_INIT, "Bringing up iface");
5612         init_status = priv->ops->rtl819x_adapter_start(dev);
5613         if(!init_status)
5614         {
5615                 RT_TRACE(COMP_ERR,"ERR!!! %s(): initialization is failed!\n", __FUNCTION__);
5616                 priv->up=priv->ieee80211->ieee_up = 0;
5617                 return -EAGAIN;
5618         }
5619         RT_TRACE(COMP_INIT, "start adapter finished\n");
5620         rtl8192_rx_enable(dev);
5621 //      rtl8192_tx_enable(dev);
5622         if(priv->ieee80211->state != IEEE80211_LINKED)
5623         ieee80211_softmac_start_protocol(priv->ieee80211);
5624         ieee80211_reset_queue(priv->ieee80211);
5625         watch_dog_timer_callback((unsigned long) dev);
5626         if(!netif_queue_stopped(dev))
5627                 netif_start_queue(dev);
5628         else
5629                 netif_wake_queue(dev);
5630
5631         /*
5632          * Make sure that drop_unencrypted is initialized as "0"
5633          * No packets will be sent in non-security mode if we had set drop_unencrypted.
5634          * ex, After kill wpa_supplicant process, make the driver up again.
5635          * drop_unencrypted remains as "1", which is set by wpa_supplicant. 2008/12/04.john
5636          */
5637         priv->ieee80211->drop_unencrypted = 0;
5638
5639         return 0;
5640 }
5641
5642
5643 int rtl8192_open(struct net_device *dev)
5644 {
5645         struct r8192_priv *priv = ieee80211_priv(dev);
5646         int ret;
5647         down(&priv->wx_sem);
5648         ret = rtl8192_up(dev);
5649         up(&priv->wx_sem);
5650         return ret;
5651
5652 }
5653
5654
5655 int rtl8192_up(struct net_device *dev)
5656 {
5657         struct r8192_priv *priv = ieee80211_priv(dev);
5658
5659         if (priv->up == 1) return -1;
5660
5661         return _rtl8192_up(dev);
5662 }
5663
5664
5665 int rtl8192_close(struct net_device *dev)
5666 {
5667         struct r8192_priv *priv = ieee80211_priv(dev);
5668         int ret;
5669
5670         down(&priv->wx_sem);
5671
5672         ret = rtl8192_down(dev);
5673
5674         up(&priv->wx_sem);
5675
5676         return ret;
5677
5678 }
5679
5680 int rtl8192_down(struct net_device *dev)
5681 {
5682         struct r8192_priv *priv = ieee80211_priv(dev);
5683         int i;
5684
5685         if (priv->up == 0) return -1;
5686
5687         priv->up=0;
5688         priv->ieee80211->ieee_up = 0;
5689         RT_TRACE(COMP_DOWN, "==========>%s()\n", __FUNCTION__);
5690 /* FIXME */
5691         if (!netif_queue_stopped(dev))
5692                 netif_stop_queue(dev);
5693
5694         rtl8192_rtx_disable(dev);
5695         //rtl8192_irq_disable(dev);
5696
5697  /* Tx related queue release */
5698         for(i = 0; i < MAX_QUEUE_SIZE; i++) {
5699                 skb_queue_purge(&priv->ieee80211->skb_waitQ [i]);
5700         }
5701         for(i = 0; i < MAX_QUEUE_SIZE; i++) {
5702                 skb_queue_purge(&priv->ieee80211->skb_aggQ [i]);
5703         }
5704
5705         for(i = 0; i < MAX_QUEUE_SIZE; i++) {
5706                 skb_queue_purge(&priv->ieee80211->skb_drv_aggQ [i]);
5707         }
5708
5709         //as cancel_delayed_work will del work->timer, so if work is not definedas struct delayed_work, it will corrupt
5710 //      flush_scheduled_work();
5711         rtl8192_cancel_deferred_work(priv);
5712         deinit_hal_dm(dev);
5713         del_timer_sync(&priv->watch_dog_timer);
5714
5715
5716         ieee80211_softmac_stop_protocol(priv->ieee80211);
5717         memset(&priv->ieee80211->current_network, 0 , offsetof(struct ieee80211_network, list));
5718         RT_TRACE(COMP_DOWN, "<==========%s()\n", __FUNCTION__);
5719
5720                 return 0;
5721 }
5722
5723
5724 void rtl8192_commit(struct net_device *dev)
5725 {
5726         struct r8192_priv *priv = ieee80211_priv(dev);
5727         int reset_status = 0;
5728         //u8 reset_times = 0;
5729         if (priv->up == 0) return ;
5730         priv->up = 0;
5731
5732         rtl8192_cancel_deferred_work(priv);
5733         del_timer_sync(&priv->watch_dog_timer);
5734         //cancel_delayed_work(&priv->SwChnlWorkItem);
5735
5736         ieee80211_softmac_stop_protocol(priv->ieee80211);
5737
5738         //rtl8192_irq_disable(dev);
5739         rtl8192_rtx_disable(dev);
5740         reset_status = _rtl8192_up(dev);
5741
5742 }
5743
5744 /*
5745 void rtl8192_restart(struct net_device *dev)
5746 {
5747         struct r8192_priv *priv = ieee80211_priv(dev);
5748 */
5749 void rtl8192_restart(struct work_struct *work)
5750 {
5751         struct r8192_priv *priv = container_of(work, struct r8192_priv, reset_wq);
5752         struct net_device *dev = priv->ieee80211->dev;
5753
5754         down(&priv->wx_sem);
5755
5756         rtl8192_commit(dev);
5757
5758         up(&priv->wx_sem);
5759 }
5760
5761 static void r8192_set_multicast(struct net_device *dev)
5762 {
5763         struct r8192_priv *priv = ieee80211_priv(dev);
5764         short promisc;
5765
5766         //down(&priv->wx_sem);
5767
5768         /* FIXME FIXME */
5769
5770         promisc = (dev->flags & IFF_PROMISC) ? 1:0;
5771
5772         if (promisc != priv->promisc)
5773         //      rtl8192_commit(dev);
5774
5775         priv->promisc = promisc;
5776
5777         //schedule_work(&priv->reset_wq);
5778         //up(&priv->wx_sem);
5779 }
5780
5781
5782 int r8192_set_mac_adr(struct net_device *dev, void *mac)
5783 {
5784         struct r8192_priv *priv = ieee80211_priv(dev);
5785         struct sockaddr *addr = mac;
5786
5787         down(&priv->wx_sem);
5788
5789         memcpy(dev->dev_addr, addr->sa_data, ETH_ALEN);
5790
5791         schedule_work(&priv->reset_wq);
5792
5793         up(&priv->wx_sem);
5794
5795         return 0;
5796 }
5797
5798 /* based on ipw2200 driver */
5799 int rtl8192_ioctl(struct net_device *dev, struct ifreq *rq, int cmd)
5800 {
5801         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
5802         struct iwreq *wrq = (struct iwreq *)rq;
5803         int ret=-1;
5804         struct ieee80211_device *ieee = priv->ieee80211;
5805         u32 key[4];
5806         u8 broadcast_addr[6] = {0xff,0xff,0xff,0xff,0xff,0xff};
5807         u8 zero_addr[6] = {0};
5808         struct iw_point *p = &wrq->u.data;
5809         struct ieee_param *ipw = NULL;//(struct ieee_param *)wrq->u.data.pointer;
5810
5811         down(&priv->wx_sem);
5812
5813
5814      if (p->length < sizeof(struct ieee_param) || !p->pointer){
5815              ret = -EINVAL;
5816              goto out;
5817         }
5818
5819      ipw = (struct ieee_param *)kmalloc(p->length, GFP_KERNEL);
5820      if (ipw == NULL){
5821              ret = -ENOMEM;
5822              goto out;
5823      }
5824      if (copy_from_user(ipw, p->pointer, p->length)) {
5825                 kfree(ipw);
5826             ret = -EFAULT;
5827             goto out;
5828         }
5829
5830         switch (cmd) {
5831             case RTL_IOCTL_WPA_SUPPLICANT:
5832         //parse here for HW security
5833                         if (ipw->cmd == IEEE_CMD_SET_ENCRYPTION)
5834                         {
5835                                 if (ipw->u.crypt.set_tx)
5836                                 {
5837                                         if (strcmp(ipw->u.crypt.alg, "CCMP") == 0)
5838                                                 ieee->pairwise_key_type = KEY_TYPE_CCMP;
5839                                         else if (strcmp(ipw->u.crypt.alg, "TKIP") == 0)
5840                                                 ieee->pairwise_key_type = KEY_TYPE_TKIP;
5841                                         else if (strcmp(ipw->u.crypt.alg, "WEP") == 0)
5842                                         {
5843                                                 if (ipw->u.crypt.key_len == 13)
5844                                                         ieee->pairwise_key_type = KEY_TYPE_WEP104;
5845                                                 else if (ipw->u.crypt.key_len == 5)
5846                                                         ieee->pairwise_key_type = KEY_TYPE_WEP40;
5847                                         }
5848                                         else
5849                                                 ieee->pairwise_key_type = KEY_TYPE_NA;
5850
5851                                         if (ieee->pairwise_key_type)
5852                                         {
5853                                 //      FIXME:these two lines below just to fix ipw interface bug, that is, it will never set mode down to driver. So treat it as ADHOC mode, if no association procedure. WB. 2009.02.04
5854                                                 if (memcmp(ieee->ap_mac_addr, zero_addr, 6) == 0)
5855                                                         ieee->iw_mode = IW_MODE_ADHOC;
5856                                                 memcpy((u8*)key, ipw->u.crypt.key, 16);
5857                                                 EnableHWSecurityConfig8192(dev);
5858                                         //we fill both index entry and 4th entry for pairwise key as in IPW interface, adhoc will only get here, so we need index entry for its default key serching!
5859                                         //added by WB.
5860                                                 setKey(dev, 4, ipw->u.crypt.idx, ieee->pairwise_key_type, (u8*)ieee->ap_mac_addr, 0, key);
5861                                                 if (ieee->iw_mode == IW_MODE_ADHOC)
5862                                                 setKey(dev, ipw->u.crypt.idx, ipw->u.crypt.idx, ieee->pairwise_key_type, (u8*)ieee->ap_mac_addr, 0, key);
5863                                         }
5864                                 }
5865                                 else //if (ipw->u.crypt.idx) //group key use idx > 0
5866                                 {
5867                                         memcpy((u8*)key, ipw->u.crypt.key, 16);
5868                                         if (strcmp(ipw->u.crypt.alg, "CCMP") == 0)
5869                                                 ieee->group_key_type= KEY_TYPE_CCMP;
5870                                         else if (strcmp(ipw->u.crypt.alg, "TKIP") == 0)
5871                                                 ieee->group_key_type = KEY_TYPE_TKIP;
5872                                         else if (strcmp(ipw->u.crypt.alg, "WEP") == 0)
5873                                         {
5874                                                 if (ipw->u.crypt.key_len == 13)
5875                                                         ieee->group_key_type = KEY_TYPE_WEP104;
5876                                                 else if (ipw->u.crypt.key_len == 5)
5877                                                         ieee->group_key_type = KEY_TYPE_WEP40;
5878                                         }
5879                                         else
5880                                                 ieee->group_key_type = KEY_TYPE_NA;
5881
5882                                         if (ieee->group_key_type)
5883                                         {
5884                                                         setKey( dev,
5885                                                                 ipw->u.crypt.idx,
5886                                                                 ipw->u.crypt.idx,               //KeyIndex
5887                                                                 ieee->group_key_type,   //KeyType
5888                                                                 broadcast_addr, //MacAddr
5889                                                                 0,              //DefaultKey
5890                                                                 key);           //KeyContent
5891                                         }
5892                                 }
5893                         }
5894 #ifdef JOHN_HWSEC_DEBUG
5895                 //john's test 0711
5896                 printk("@@ wrq->u pointer = ");
5897                 for(i=0;i<wrq->u.data.length;i++){
5898                         if(i%10==0) printk("\n");
5899                         printk( "%8x|", ((u32*)wrq->u.data.pointer)[i] );
5900                 }
5901                 printk("\n");
5902 #endif /*JOHN_HWSEC_DEBUG*/
5903                 ret = ieee80211_wpa_supplicant_ioctl(priv->ieee80211, &wrq->u.data);
5904                 break;
5905
5906             default:
5907                 ret = -EOPNOTSUPP;
5908                 break;
5909         }
5910         kfree(ipw);
5911         ipw = NULL;
5912 out:
5913         up(&priv->wx_sem);
5914         return ret;
5915 }
5916
5917 u8 rtl8192SU_HwRateToMRate(bool bIsHT, u8 rate,bool bFirstAMPDU)
5918 {
5919
5920         u8      ret_rate = 0x02;
5921
5922         if( bFirstAMPDU )
5923         {
5924         if(!bIsHT)
5925         {
5926                 switch(rate)
5927                 {
5928
5929                         case DESC92S_RATE1M:            ret_rate = MGN_1M;              break;
5930                         case DESC92S_RATE2M:            ret_rate = MGN_2M;              break;
5931                         case DESC92S_RATE5_5M:          ret_rate = MGN_5_5M;            break;
5932                         case DESC92S_RATE11M:           ret_rate = MGN_11M;             break;
5933                         case DESC92S_RATE6M:            ret_rate = MGN_6M;              break;
5934                         case DESC92S_RATE9M:            ret_rate = MGN_9M;              break;
5935                         case DESC92S_RATE12M:           ret_rate = MGN_12M;             break;
5936                         case DESC92S_RATE18M:           ret_rate = MGN_18M;             break;
5937                         case DESC92S_RATE24M:           ret_rate = MGN_24M;             break;
5938                         case DESC92S_RATE36M:           ret_rate = MGN_36M;             break;
5939                         case DESC92S_RATE48M:           ret_rate = MGN_48M;             break;
5940                         case DESC92S_RATE54M:           ret_rate = MGN_54M;             break;
5941
5942                         default:
5943                                 RT_TRACE(COMP_RECV, "HwRateToMRate90(): Non supported Rate [%x], bIsHT = %d!!!\n", rate, bIsHT);
5944                                         break;
5945         }
5946                 }
5947                 else
5948         {
5949                 switch(rate)
5950                 {
5951
5952                         case DESC92S_RATEMCS0:  ret_rate = MGN_MCS0;            break;
5953                         case DESC92S_RATEMCS1:  ret_rate = MGN_MCS1;            break;
5954                         case DESC92S_RATEMCS2:  ret_rate = MGN_MCS2;            break;
5955                         case DESC92S_RATEMCS3:  ret_rate = MGN_MCS3;            break;
5956                         case DESC92S_RATEMCS4:  ret_rate = MGN_MCS4;            break;
5957                         case DESC92S_RATEMCS5:  ret_rate = MGN_MCS5;            break;
5958                         case DESC92S_RATEMCS6:  ret_rate = MGN_MCS6;            break;
5959                         case DESC92S_RATEMCS7:  ret_rate = MGN_MCS7;            break;
5960                         case DESC92S_RATEMCS8:  ret_rate = MGN_MCS8;            break;
5961                         case DESC92S_RATEMCS9:  ret_rate = MGN_MCS9;            break;
5962                         case DESC92S_RATEMCS10: ret_rate = MGN_MCS10;   break;
5963                         case DESC92S_RATEMCS11: ret_rate = MGN_MCS11;   break;
5964                         case DESC92S_RATEMCS12: ret_rate = MGN_MCS12;   break;
5965                         case DESC92S_RATEMCS13: ret_rate = MGN_MCS13;   break;
5966                         case DESC92S_RATEMCS14: ret_rate = MGN_MCS14;   break;
5967                         case DESC92S_RATEMCS15: ret_rate = MGN_MCS15;   break;
5968                         case DESC92S_RATEMCS32: ret_rate = (0x80|0x20); break;
5969
5970                         default:
5971                                         RT_TRACE(COMP_RECV, "HwRateToMRate92S(): Non supported Rate [%x], bIsHT = %d!!!\n",rate, bIsHT );
5972                                 break;
5973                 }
5974
5975         }
5976         }
5977         else
5978         {
5979                 switch(rate)
5980                 {
5981
5982                         case DESC92S_RATE1M:    ret_rate = MGN_1M;              break;
5983                         case DESC92S_RATE2M:    ret_rate = MGN_2M;              break;
5984                         case DESC92S_RATE5_5M:  ret_rate = MGN_5_5M;            break;
5985                         case DESC92S_RATE11M:   ret_rate = MGN_11M;             break;
5986                         case DESC92S_RATE6M:    ret_rate = MGN_6M;              break;
5987                         case DESC92S_RATE9M:    ret_rate = MGN_9M;              break;
5988                         case DESC92S_RATE12M:   ret_rate = MGN_12M;             break;
5989                         case DESC92S_RATE18M:   ret_rate = MGN_18M;             break;
5990                         case DESC92S_RATE24M:   ret_rate = MGN_24M;             break;
5991                         case DESC92S_RATE36M:   ret_rate = MGN_36M;             break;
5992                         case DESC92S_RATE48M:   ret_rate = MGN_48M;             break;
5993                         case DESC92S_RATE54M:   ret_rate = MGN_54M;             break;
5994                         case DESC92S_RATEMCS0:  ret_rate = MGN_MCS0;            break;
5995                         case DESC92S_RATEMCS1:  ret_rate = MGN_MCS1;            break;
5996                         case DESC92S_RATEMCS2:  ret_rate = MGN_MCS2;            break;
5997                         case DESC92S_RATEMCS3:  ret_rate = MGN_MCS3;            break;
5998                         case DESC92S_RATEMCS4:  ret_rate = MGN_MCS4;            break;
5999                         case DESC92S_RATEMCS5:  ret_rate = MGN_MCS5;            break;
6000                         case DESC92S_RATEMCS6:  ret_rate = MGN_MCS6;            break;
6001                         case DESC92S_RATEMCS7:  ret_rate = MGN_MCS7;            break;
6002                         case DESC92S_RATEMCS8:  ret_rate = MGN_MCS8;            break;
6003                         case DESC92S_RATEMCS9:  ret_rate = MGN_MCS9;            break;
6004                         case DESC92S_RATEMCS10: ret_rate = MGN_MCS10;   break;
6005                         case DESC92S_RATEMCS11: ret_rate = MGN_MCS11;   break;
6006                         case DESC92S_RATEMCS12: ret_rate = MGN_MCS12;   break;
6007                         case DESC92S_RATEMCS13: ret_rate = MGN_MCS13;   break;
6008                         case DESC92S_RATEMCS14: ret_rate = MGN_MCS14;   break;
6009                         case DESC92S_RATEMCS15: ret_rate = MGN_MCS15;   break;
6010                         case DESC92S_RATEMCS32: ret_rate = (0x80|0x20); break;
6011
6012                         default:
6013                                 RT_TRACE(COMP_RECV, "HwRateToMRate92S(): Non supported Rate [%x], bIsHT = %d!!!\n",rate, bIsHT );
6014                                 break;
6015                         }
6016         }
6017         return ret_rate;
6018 }
6019
6020 u8 HwRateToMRate90(bool bIsHT, u8 rate)
6021 {
6022         u8  ret_rate = 0xff;
6023
6024         if(!bIsHT) {
6025                 switch(rate) {
6026                         case DESC90_RATE1M:   ret_rate = MGN_1M;         break;
6027                         case DESC90_RATE2M:   ret_rate = MGN_2M;         break;
6028                         case DESC90_RATE5_5M: ret_rate = MGN_5_5M;       break;
6029                         case DESC90_RATE11M:  ret_rate = MGN_11M;        break;
6030                         case DESC90_RATE6M:   ret_rate = MGN_6M;         break;
6031                         case DESC90_RATE9M:   ret_rate = MGN_9M;         break;
6032                         case DESC90_RATE12M:  ret_rate = MGN_12M;        break;
6033                         case DESC90_RATE18M:  ret_rate = MGN_18M;        break;
6034                         case DESC90_RATE24M:  ret_rate = MGN_24M;        break;
6035                         case DESC90_RATE36M:  ret_rate = MGN_36M;        break;
6036                         case DESC90_RATE48M:  ret_rate = MGN_48M;        break;
6037                         case DESC90_RATE54M:  ret_rate = MGN_54M;        break;
6038
6039                         default:
6040                                 ret_rate = 0xff;
6041                                 RT_TRACE(COMP_RECV, "HwRateToMRate90(): Non supported Rate [%x], bIsHT = %d!!!\n", rate, bIsHT);
6042                                 break;
6043                 }
6044
6045         } else {
6046                 switch(rate) {
6047                         case DESC90_RATEMCS0:   ret_rate = MGN_MCS0;    break;
6048                         case DESC90_RATEMCS1:   ret_rate = MGN_MCS1;    break;
6049                         case DESC90_RATEMCS2:   ret_rate = MGN_MCS2;    break;
6050                         case DESC90_RATEMCS3:   ret_rate = MGN_MCS3;    break;
6051                         case DESC90_RATEMCS4:   ret_rate = MGN_MCS4;    break;
6052                         case DESC90_RATEMCS5:   ret_rate = MGN_MCS5;    break;
6053                         case DESC90_RATEMCS6:   ret_rate = MGN_MCS6;    break;
6054                         case DESC90_RATEMCS7:   ret_rate = MGN_MCS7;    break;
6055                         case DESC90_RATEMCS8:   ret_rate = MGN_MCS8;    break;
6056                         case DESC90_RATEMCS9:   ret_rate = MGN_MCS9;    break;
6057                         case DESC90_RATEMCS10:  ret_rate = MGN_MCS10;   break;
6058                         case DESC90_RATEMCS11:  ret_rate = MGN_MCS11;   break;
6059                         case DESC90_RATEMCS12:  ret_rate = MGN_MCS12;   break;
6060                         case DESC90_RATEMCS13:  ret_rate = MGN_MCS13;   break;
6061                         case DESC90_RATEMCS14:  ret_rate = MGN_MCS14;   break;
6062                         case DESC90_RATEMCS15:  ret_rate = MGN_MCS15;   break;
6063                         case DESC90_RATEMCS32:  ret_rate = (0x80|0x20); break;
6064
6065                         default:
6066                                 ret_rate = 0xff;
6067                                 RT_TRACE(COMP_RECV, "HwRateToMRate90(): Non supported Rate [%x], bIsHT = %d!!!\n",rate, bIsHT);
6068                                 break;
6069                 }
6070         }
6071
6072         return ret_rate;
6073 }
6074
6075 /**
6076  * Function:     UpdateRxPktTimeStamp
6077  * Overview:     Recored down the TSF time stamp when receiving a packet
6078  *
6079  * Input:
6080  *       PADAPTER        Adapter
6081  *       PRT_RFD         pRfd,
6082  *
6083  * Output:
6084  *       PRT_RFD         pRfd
6085  *                               (pRfd->Status.TimeStampHigh is updated)
6086  *                               (pRfd->Status.TimeStampLow is updated)
6087  * Return:
6088  *               None
6089  */
6090 void UpdateRxPktTimeStamp8190 (struct net_device *dev, struct ieee80211_rx_stats *stats)
6091 {
6092         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
6093
6094         if(stats->bIsAMPDU && !stats->bFirstMPDU) {
6095                 stats->mac_time[0] = priv->LastRxDescTSFLow;
6096                 stats->mac_time[1] = priv->LastRxDescTSFHigh;
6097         } else {
6098                 priv->LastRxDescTSFLow = stats->mac_time[0];
6099                 priv->LastRxDescTSFHigh = stats->mac_time[1];
6100         }
6101 }
6102
6103 //by amy 080606
6104
6105 long rtl819x_translate_todbm(u8 signal_strength_index   )// 0-100 index.
6106 {
6107         long    signal_power; // in dBm.
6108
6109         // Translate to dBm (x=0.5y-95).
6110         signal_power = (long)((signal_strength_index + 1) >> 1);
6111         signal_power -= 95;
6112
6113         return signal_power;
6114 }
6115
6116
6117 /* 2008/01/22 MH We can not delcare RSSI/EVM total value of sliding window to
6118     be a local static. Otherwise, it may increase when we return from S3/S4. The
6119     value will be kept in memory or disk. We must delcare the value in adapter
6120     and it will be reinitialized when return from S3/S4. */
6121 void rtl8192_process_phyinfo(struct r8192_priv * priv,u8* buffer, struct ieee80211_rx_stats * pprevious_stats, struct ieee80211_rx_stats * pcurrent_stats)
6122 {
6123         bool bcheck = false;
6124         u8      rfpath;
6125         u32     nspatial_stream, tmp_val;
6126         //u8    i;
6127         static u32 slide_rssi_index=0, slide_rssi_statistics=0;
6128         static u32 slide_evm_index=0, slide_evm_statistics=0;
6129         static u32 last_rssi=0, last_evm=0;
6130
6131         static u32 slide_beacon_adc_pwdb_index=0, slide_beacon_adc_pwdb_statistics=0;
6132         static u32 last_beacon_adc_pwdb=0;
6133
6134         struct ieee80211_hdr_3addr *hdr;
6135         u16 sc ;
6136         unsigned int frag,seq;
6137         hdr = (struct ieee80211_hdr_3addr *)buffer;
6138         sc = le16_to_cpu(hdr->seq_ctrl);
6139         frag = WLAN_GET_SEQ_FRAG(sc);
6140         seq = WLAN_GET_SEQ_SEQ(sc);
6141         //cosa add 04292008 to record the sequence number
6142         pcurrent_stats->Seq_Num = seq;
6143         //
6144         // Check whether we should take the previous packet into accounting
6145         //
6146         if(!pprevious_stats->bIsAMPDU)
6147         {
6148                 // if previous packet is not aggregated packet
6149                 bcheck = true;
6150         }else
6151         {
6152         }
6153
6154
6155         if(slide_rssi_statistics++ >= PHY_RSSI_SLID_WIN_MAX)
6156         {
6157                 slide_rssi_statistics = PHY_RSSI_SLID_WIN_MAX;
6158                 last_rssi = priv->stats.slide_signal_strength[slide_rssi_index];
6159                 priv->stats.slide_rssi_total -= last_rssi;
6160         }
6161         priv->stats.slide_rssi_total += pprevious_stats->SignalStrength;
6162
6163         priv->stats.slide_signal_strength[slide_rssi_index++] = pprevious_stats->SignalStrength;
6164         if(slide_rssi_index >= PHY_RSSI_SLID_WIN_MAX)
6165                 slide_rssi_index = 0;
6166
6167         // <1> Showed on UI for user, in dbm
6168         tmp_val = priv->stats.slide_rssi_total/slide_rssi_statistics;
6169         priv->stats.signal_strength = rtl819x_translate_todbm((u8)tmp_val);
6170         pcurrent_stats->rssi = priv->stats.signal_strength;
6171         //
6172         // If the previous packet does not match the criteria, neglect it
6173         //
6174         if(!pprevious_stats->bPacketMatchBSSID)
6175         {
6176                 if(!pprevious_stats->bToSelfBA)
6177                         return;
6178         }
6179
6180         if(!bcheck)
6181                 return;
6182
6183
6184         //rtl8190_process_cck_rxpathsel(priv,pprevious_stats);//only rtl8190 supported
6185
6186         //
6187         // Check RSSI
6188         //
6189         priv->stats.num_process_phyinfo++;
6190
6191         /* record the general signal strength to the sliding window. */
6192
6193
6194         // <2> Showed on UI for engineering
6195         // hardware does not provide rssi information for each rf path in CCK
6196         if(!pprevious_stats->bIsCCK && (pprevious_stats->bPacketToSelf || pprevious_stats->bToSelfBA))
6197         {
6198                 for (rfpath = RF90_PATH_A; rfpath < priv->NumTotalRFPath; rfpath++)
6199                 {
6200                      if (!rtl8192_phy_CheckIsLegalRFPath(priv->ieee80211->dev, rfpath))
6201                                  continue;
6202
6203                         //Fixed by Jacken 2008-03-20
6204                         if(priv->stats.rx_rssi_percentage[rfpath] == 0)
6205                         {
6206                                 priv->stats.rx_rssi_percentage[rfpath] = pprevious_stats->RxMIMOSignalStrength[rfpath];
6207                                 //DbgPrint("MIMO RSSI initialize \n");
6208                         }
6209                         if(pprevious_stats->RxMIMOSignalStrength[rfpath]  > priv->stats.rx_rssi_percentage[rfpath])
6210                         {
6211                                 priv->stats.rx_rssi_percentage[rfpath] =
6212                                         ( (priv->stats.rx_rssi_percentage[rfpath]*(Rx_Smooth_Factor-1)) +
6213                                         (pprevious_stats->RxMIMOSignalStrength[rfpath])) /(Rx_Smooth_Factor);
6214                                 priv->stats.rx_rssi_percentage[rfpath] = priv->stats.rx_rssi_percentage[rfpath]  + 1;
6215                         }
6216                         else
6217                         {
6218                                 priv->stats.rx_rssi_percentage[rfpath] =
6219                                         ( (priv->stats.rx_rssi_percentage[rfpath]*(Rx_Smooth_Factor-1)) +
6220                                         (pprevious_stats->RxMIMOSignalStrength[rfpath])) /(Rx_Smooth_Factor);
6221                         }
6222                         RT_TRACE(COMP_DBG,"priv->stats.rx_rssi_percentage[rfPath]  = %d \n" ,priv->stats.rx_rssi_percentage[rfpath] );
6223                 }
6224         }
6225
6226
6227         //
6228         // Check PWDB.
6229         //
6230         RT_TRACE(COMP_RXDESC, "Smooth %s PWDB = %d\n",
6231                                 pprevious_stats->bIsCCK? "CCK": "OFDM",
6232                                 pprevious_stats->RxPWDBAll);
6233
6234         if(pprevious_stats->bPacketBeacon)
6235         {
6236 /* record the beacon pwdb to the sliding window. */
6237                 if(slide_beacon_adc_pwdb_statistics++ >= PHY_Beacon_RSSI_SLID_WIN_MAX)
6238                 {
6239                         slide_beacon_adc_pwdb_statistics = PHY_Beacon_RSSI_SLID_WIN_MAX;
6240                         last_beacon_adc_pwdb = priv->stats.Slide_Beacon_pwdb[slide_beacon_adc_pwdb_index];
6241                         priv->stats.Slide_Beacon_Total -= last_beacon_adc_pwdb;
6242                         //DbgPrint("slide_beacon_adc_pwdb_index = %d, last_beacon_adc_pwdb = %d, Adapter->RxStats.Slide_Beacon_Total = %d\n",
6243                         //      slide_beacon_adc_pwdb_index, last_beacon_adc_pwdb, Adapter->RxStats.Slide_Beacon_Total);
6244                 }
6245                 priv->stats.Slide_Beacon_Total += pprevious_stats->RxPWDBAll;
6246                 priv->stats.Slide_Beacon_pwdb[slide_beacon_adc_pwdb_index] = pprevious_stats->RxPWDBAll;
6247                 //DbgPrint("slide_beacon_adc_pwdb_index = %d, pPreviousRfd->Status.RxPWDBAll = %d\n", slide_beacon_adc_pwdb_index, pPreviousRfd->Status.RxPWDBAll);
6248                 slide_beacon_adc_pwdb_index++;
6249                 if(slide_beacon_adc_pwdb_index >= PHY_Beacon_RSSI_SLID_WIN_MAX)
6250                         slide_beacon_adc_pwdb_index = 0;
6251                 pprevious_stats->RxPWDBAll = priv->stats.Slide_Beacon_Total/slide_beacon_adc_pwdb_statistics;
6252                 if(pprevious_stats->RxPWDBAll >= 3)
6253                         pprevious_stats->RxPWDBAll -= 3;
6254         }
6255
6256         RT_TRACE(COMP_RXDESC, "Smooth %s PWDB = %d\n",
6257                                 pprevious_stats->bIsCCK? "CCK": "OFDM",
6258                                 pprevious_stats->RxPWDBAll);
6259
6260
6261         if(pprevious_stats->bPacketToSelf || pprevious_stats->bPacketBeacon || pprevious_stats->bToSelfBA)
6262         {
6263                 if(priv->undecorated_smoothed_pwdb < 0) // initialize
6264                 {
6265                         priv->undecorated_smoothed_pwdb = pprevious_stats->RxPWDBAll;
6266                         //DbgPrint("First pwdb initialize \n");
6267                 }
6268 #if 1
6269                 if(pprevious_stats->RxPWDBAll > (u32)priv->undecorated_smoothed_pwdb)
6270                 {
6271                         priv->undecorated_smoothed_pwdb =
6272                                         ( ((priv->undecorated_smoothed_pwdb)*(Rx_Smooth_Factor-1)) +
6273                                         (pprevious_stats->RxPWDBAll)) /(Rx_Smooth_Factor);
6274                         priv->undecorated_smoothed_pwdb = priv->undecorated_smoothed_pwdb + 1;
6275                 }
6276                 else
6277                 {
6278                         priv->undecorated_smoothed_pwdb =
6279                                         ( ((priv->undecorated_smoothed_pwdb)*(Rx_Smooth_Factor-1)) +
6280                                         (pprevious_stats->RxPWDBAll)) /(Rx_Smooth_Factor);
6281                 }
6282 #else
6283                 //Fixed by Jacken 2008-03-20
6284                 if(pPreviousRfd->Status.RxPWDBAll > (u32)pHalData->UndecoratedSmoothedPWDB)
6285                 {
6286                         pHalData->UndecoratedSmoothedPWDB =
6287                                         ( ((pHalData->UndecoratedSmoothedPWDB)* 5) + (pPreviousRfd->Status.RxPWDBAll)) / 6;
6288                         pHalData->UndecoratedSmoothedPWDB = pHalData->UndecoratedSmoothedPWDB + 1;
6289                 }
6290                 else
6291                 {
6292                         pHalData->UndecoratedSmoothedPWDB =
6293                                         ( ((pHalData->UndecoratedSmoothedPWDB)* 5) + (pPreviousRfd->Status.RxPWDBAll)) / 6;
6294                 }
6295 #endif
6296
6297         }
6298
6299         //
6300         // Check EVM
6301         //
6302         /* record the general EVM to the sliding window. */
6303         if(pprevious_stats->SignalQuality == 0)
6304         {
6305         }
6306         else
6307         {
6308                 if(pprevious_stats->bPacketToSelf || pprevious_stats->bPacketBeacon || pprevious_stats->bToSelfBA){
6309                         if(slide_evm_statistics++ >= PHY_RSSI_SLID_WIN_MAX){
6310                                 slide_evm_statistics = PHY_RSSI_SLID_WIN_MAX;
6311                                 last_evm = priv->stats.slide_evm[slide_evm_index];
6312                                 priv->stats.slide_evm_total -= last_evm;
6313                         }
6314
6315                         priv->stats.slide_evm_total += pprevious_stats->SignalQuality;
6316
6317                         priv->stats.slide_evm[slide_evm_index++] = pprevious_stats->SignalQuality;
6318                         if(slide_evm_index >= PHY_RSSI_SLID_WIN_MAX)
6319                                 slide_evm_index = 0;
6320
6321                         // <1> Showed on UI for user, in percentage.
6322                         tmp_val = priv->stats.slide_evm_total/slide_evm_statistics;
6323                         priv->stats.signal_quality = tmp_val;
6324                         //cosa add 10/11/2007, Showed on UI for user in Windows Vista, for Link quality.
6325                         priv->stats.last_signal_strength_inpercent = tmp_val;
6326                 }
6327
6328                 // <2> Showed on UI for engineering
6329                 if(pprevious_stats->bPacketToSelf || pprevious_stats->bPacketBeacon || pprevious_stats->bToSelfBA)
6330                 {
6331                         for(nspatial_stream = 0; nspatial_stream<2 ; nspatial_stream++) // 2 spatial stream
6332                         {
6333                                 if(pprevious_stats->RxMIMOSignalQuality[nspatial_stream] != -1)
6334                                 {
6335                                         if(priv->stats.rx_evm_percentage[nspatial_stream] == 0) // initialize
6336                                         {
6337                                                 priv->stats.rx_evm_percentage[nspatial_stream] = pprevious_stats->RxMIMOSignalQuality[nspatial_stream];
6338                                         }
6339                                         priv->stats.rx_evm_percentage[nspatial_stream] =
6340                                                 ( (priv->stats.rx_evm_percentage[nspatial_stream]* (Rx_Smooth_Factor-1)) +
6341                                                 (pprevious_stats->RxMIMOSignalQuality[nspatial_stream]* 1)) / (Rx_Smooth_Factor);
6342                                 }
6343                         }
6344                 }
6345         }
6346
6347
6348 }
6349
6350 /*-----------------------------------------------------------------------------
6351  * Function:    rtl819x_query_rxpwrpercentage()
6352  *
6353  * Overview:
6354  *
6355  * Input:               char            antpower
6356  *
6357  * Output:              NONE
6358  *
6359  * Return:              0-100 percentage
6360  *
6361  * Revised History:
6362  *      When            Who             Remark
6363  *      05/26/2008      amy             Create Version 0 porting from windows code.
6364  *
6365  *---------------------------------------------------------------------------*/
6366 static u8 rtl819x_query_rxpwrpercentage(
6367         char            antpower
6368         )
6369 {
6370         if ((antpower <= -100) || (antpower >= 20))
6371         {
6372                 return  0;
6373         }
6374         else if (antpower >= 0)
6375         {
6376                 return  100;
6377         }
6378         else
6379         {
6380                 return  (100+antpower);
6381         }
6382
6383 }       /* QueryRxPwrPercentage */
6384
6385 static u8
6386 rtl819x_evm_dbtopercentage(
6387     char value
6388     )
6389 {
6390     char ret_val;
6391
6392     ret_val = value;
6393
6394     if(ret_val >= 0)
6395         ret_val = 0;
6396     if(ret_val <= -33)
6397         ret_val = -33;
6398     ret_val = 0 - ret_val;
6399     ret_val*=3;
6400         if(ret_val == 99)
6401                 ret_val = 100;
6402     return(ret_val);
6403 }
6404 //
6405 //      Description:
6406 //      We want good-looking for signal strength/quality
6407 //      2007/7/19 01:09, by cosa.
6408 //
6409 long
6410 rtl819x_signal_scale_mapping(
6411         long currsig
6412         )
6413 {
6414         long retsig;
6415
6416         // Step 1. Scale mapping.
6417         if(currsig >= 61 && currsig <= 100)
6418         {
6419                 retsig = 90 + ((currsig - 60) / 4);
6420         }
6421         else if(currsig >= 41 && currsig <= 60)
6422         {
6423                 retsig = 78 + ((currsig - 40) / 2);
6424         }
6425         else if(currsig >= 31 && currsig <= 40)
6426         {
6427                 retsig = 66 + (currsig - 30);
6428         }
6429         else if(currsig >= 21 && currsig <= 30)
6430         {
6431                 retsig = 54 + (currsig - 20);
6432         }
6433         else if(currsig >= 5 && currsig <= 20)
6434         {
6435                 retsig = 42 + (((currsig - 5) * 2) / 3);
6436         }
6437         else if(currsig == 4)
6438         {
6439                 retsig = 36;
6440         }
6441         else if(currsig == 3)
6442         {
6443                 retsig = 27;
6444         }
6445         else if(currsig == 2)
6446         {
6447                 retsig = 18;
6448         }
6449         else if(currsig == 1)
6450         {
6451                 retsig = 9;
6452         }
6453         else
6454         {
6455                 retsig = currsig;
6456         }
6457
6458         return retsig;
6459 }
6460
6461 /*-----------------------------------------------------------------------------
6462  * Function:    QueryRxPhyStatus8192S()
6463  *
6464  * Overview:
6465  *
6466  * Input:               NONE
6467  *
6468  * Output:              NONE
6469  *
6470  * Return:              NONE
6471  *
6472  * Revised History:
6473  *      When            Who             Remark
6474  *      06/01/2007      MHC             Create Version 0.
6475  *      06/05/2007      MHC             Accordign to HW's new data sheet, we add CCK and OFDM
6476  *                                              descriptor definition.
6477  *      07/04/2007      MHC             According to Jerry and Bryant's document. We read
6478  *                                              ir_isolation and ext_lna for RF's init value and use
6479  *                                              to compensate RSSI after receiving packets.
6480  *      09/10/2008      MHC             Modify name and PHY status field for 92SE.
6481  *      09/19/2008      MHC             Add CCK/OFDM SS/SQ for 92S series.
6482  *
6483  *---------------------------------------------------------------------------*/
6484 static void rtl8192SU_query_rxphystatus(
6485         struct r8192_priv * priv,
6486         struct ieee80211_rx_stats * pstats,
6487         rx_desc_819x_usb        *pDesc,
6488         rx_drvinfo_819x_usb  * pdrvinfo,
6489         struct ieee80211_rx_stats * precord_stats,
6490         bool bpacket_match_bssid,
6491         bool bpacket_toself,
6492         bool bPacketBeacon,
6493         bool bToSelfBA
6494         )
6495 {
6496         //PRT_RFD_STATUS                pRtRfdStatus = &(pRfd->Status);
6497         //PHY_STS_CCK_8192S_T   *pCck_buf;
6498         phy_sts_cck_819xusb_t   *       pcck_buf;
6499         phy_ofdm_rx_status_rxsc_sgien_exintfflag* prxsc;
6500         //u8                            *prxpkt;
6501         //u8                            i, max_spatial_stream, tmp_rxsnr, tmp_rxevm, rxsc_sgien_exflg;
6502         u8                              i, max_spatial_stream, rxsc_sgien_exflg;
6503         char                            rx_pwr[4], rx_pwr_all=0;
6504         //long                          rx_avg_pwr = 0;
6505         //char                          rx_snrX, rx_evmX;
6506         u8                              evm, pwdb_all;
6507         u32                             RSSI, total_rssi=0;//, total_evm=0;
6508 //      long                            signal_strength_index = 0;
6509         u8                              is_cck_rate=0;
6510         u8                              rf_rx_num = 0;
6511
6512
6513
6514         priv->stats.numqry_phystatus++;
6515
6516         is_cck_rate = rx_hal_is_cck_rate(pDesc);
6517
6518         // Record it for next packet processing
6519         memset(precord_stats, 0, sizeof(struct ieee80211_rx_stats));
6520         pstats->bPacketMatchBSSID = precord_stats->bPacketMatchBSSID = bpacket_match_bssid;
6521         pstats->bPacketToSelf = precord_stats->bPacketToSelf = bpacket_toself;
6522         pstats->bIsCCK = precord_stats->bIsCCK = is_cck_rate;//RX_HAL_IS_CCK_RATE(pDrvInfo);
6523         pstats->bPacketBeacon = precord_stats->bPacketBeacon = bPacketBeacon;
6524         pstats->bToSelfBA = precord_stats->bToSelfBA = bToSelfBA;
6525
6526
6527         pstats->RxMIMOSignalQuality[0] = -1;
6528         pstats->RxMIMOSignalQuality[1] = -1;
6529         precord_stats->RxMIMOSignalQuality[0] = -1;
6530         precord_stats->RxMIMOSignalQuality[1] = -1;
6531
6532         if(is_cck_rate)
6533         {
6534                 u8 report;//, tmp_pwdb;
6535                 //char cck_adc_pwdb[4];
6536
6537                 // CCK Driver info Structure is not the same as OFDM packet.
6538                 pcck_buf = (phy_sts_cck_819xusb_t *)pdrvinfo;
6539
6540                 //
6541                 // (1)Hardware does not provide RSSI for CCK
6542                 //
6543
6544                 //
6545                 // (2)PWDB, Average PWDB cacluated by hardware (for rate adaptive)
6546                 //
6547
6548                 priv->stats.numqry_phystatusCCK++;
6549
6550                 if(!priv->bCckHighPower)
6551                 {
6552                         report = pcck_buf->cck_agc_rpt & 0xc0;
6553                         report = report>>6;
6554                         switch(report)
6555                         {
6556                                 //Fixed by Jacken from Bryant 2008-03-20
6557                                 //Original value is -38 , -26 , -14 , -2
6558                                 //Fixed value is -35 , -23 , -11 , 6
6559                                 case 0x3:
6560                                         rx_pwr_all = -35 - (pcck_buf->cck_agc_rpt & 0x3e);
6561                                         break;
6562                                 case 0x2:
6563                                         rx_pwr_all = -23 - (pcck_buf->cck_agc_rpt & 0x3e);
6564                                         break;
6565                                 case 0x1:
6566                                         rx_pwr_all = -11 - (pcck_buf->cck_agc_rpt & 0x3e);
6567                                         break;
6568                                 case 0x0:
6569                                         rx_pwr_all = 8 - (pcck_buf->cck_agc_rpt & 0x3e);//6->8
6570                                         break;
6571                         }
6572                 }
6573                 else
6574                 {
6575                         report = pdrvinfo->cfosho[0] & 0x60;
6576                         report = report>>5;
6577                         switch(report)
6578                         {
6579                                 case 0x3:
6580                                         rx_pwr_all = -35 - ((pcck_buf->cck_agc_rpt & 0x1f)<<1) ;
6581                                         break;
6582                                 case 0x2:
6583                                         rx_pwr_all = -23 - ((pcck_buf->cck_agc_rpt & 0x1f)<<1);
6584                                         break;
6585                                 case 0x1:
6586                                         rx_pwr_all = -11 - ((pcck_buf->cck_agc_rpt & 0x1f)<<1) ;
6587                                         break;
6588                                 case 0x0:
6589                                         rx_pwr_all = -8 - ((pcck_buf->cck_agc_rpt & 0x1f)<<1) ;//6->-8
6590                                         break;
6591                         }
6592                 }
6593
6594                 pwdb_all = rtl819x_query_rxpwrpercentage(rx_pwr_all);//check it
6595                 pstats->RxPWDBAll = precord_stats->RxPWDBAll = pwdb_all;
6596                 //pstats->RecvSignalPower = pwdb_all;
6597                 pstats->RecvSignalPower = rx_pwr_all;
6598
6599                 //
6600                 // (3) Get Signal Quality (EVM)
6601                 //
6602         //if(bpacket_match_bssid)
6603         {
6604                         u8      sq;
6605
6606                         if(pstats->RxPWDBAll > 40)
6607                         {
6608                                 sq = 100;
6609                         }else
6610                         {
6611                                 sq = pcck_buf->sq_rpt;
6612
6613                                 if(pcck_buf->sq_rpt > 64)
6614                                         sq = 0;
6615                                 else if (pcck_buf->sq_rpt < 20)
6616                                         sq = 100;
6617                                 else
6618                                         sq = ((64-sq) * 100) / 44;
6619                         }
6620                         pstats->SignalQuality = precord_stats->SignalQuality = sq;
6621                         pstats->RxMIMOSignalQuality[0] = precord_stats->RxMIMOSignalQuality[0] = sq;
6622                         pstats->RxMIMOSignalQuality[1] = precord_stats->RxMIMOSignalQuality[1] = -1;
6623                 }
6624         }
6625         else
6626         {
6627                 priv->stats.numqry_phystatusHT++;
6628
6629                 // 2008/09/19 MH For 92S debug, RX RF path always enable!!
6630                 priv->brfpath_rxenable[0] = priv->brfpath_rxenable[1] = TRUE;
6631
6632                 //
6633                 // (1)Get RSSI for HT rate
6634                 //
6635                 //for(i=RF90_PATH_A; i<priv->NumTotalRFPath; i++)
6636                 for(i=RF90_PATH_A; i<RF90_PATH_MAX; i++)
6637                 {
6638                         // 2008/01/30 MH we will judge RF RX path now.
6639                         if (priv->brfpath_rxenable[i])
6640                                 rf_rx_num++;
6641                         //else
6642                         //      continue;
6643
6644                 //if (!rtl8192_phy_CheckIsLegalRFPath(priv->ieee80211->dev, i))
6645                 //              continue;
6646
6647                         //Fixed by Jacken from Bryant 2008-03-20
6648                         //Original value is 106
6649                         //rx_pwr[i] = ((pofdm_buf->trsw_gain_X[i]&0x3F)*2) - 106;
6650                         rx_pwr[i] = ((pdrvinfo->gain_trsw[i]&0x3F)*2) - 110;
6651
6652                         /* Translate DBM to percentage. */
6653                         RSSI = rtl819x_query_rxpwrpercentage(rx_pwr[i]);        //check ok
6654                         total_rssi += RSSI;
6655                         RT_TRACE(COMP_RF, "RF-%d RXPWR=%x RSSI=%d\n", i, rx_pwr[i], RSSI);
6656
6657                         //Get Rx snr value in DB
6658                         //tmp_rxsnr =   pofdm_buf->rxsnr_X[i];
6659                         //rx_snrX = (char)(tmp_rxsnr);
6660                         //rx_snrX /= 2;
6661                         //priv->stats.rxSNRdB[i] = (long)rx_snrX;
6662                         priv->stats.rxSNRdB[i] = (long)(pdrvinfo->rxsnr[i]/2);
6663
6664                         /* Translate DBM to percentage. */
6665                         //RSSI = rtl819x_query_rxpwrpercentage(rx_pwr[i]);
6666                         //total_rssi += RSSI;
6667
6668                         /* Record Signal Strength for next packet */
6669                         //if(bpacket_match_bssid)
6670                         {
6671                                 pstats->RxMIMOSignalStrength[i] =(u8) RSSI;
6672                                 precord_stats->RxMIMOSignalStrength[i] =(u8) RSSI;
6673                         }
6674                 }
6675
6676
6677                 //
6678                 // (2)PWDB, Average PWDB cacluated by hardware (for rate adaptive)
6679                 //
6680                 //Fixed by Jacken from Bryant 2008-03-20
6681                 //Original value is 106
6682                 //rx_pwr_all = (((pofdm_buf->pwdb_all ) >> 1 )& 0x7f) -106;
6683                 rx_pwr_all = (((pdrvinfo->pwdb_all ) >> 1 )& 0x7f) -106;
6684                 pwdb_all = rtl819x_query_rxpwrpercentage(rx_pwr_all);
6685
6686                 pstats->RxPWDBAll = precord_stats->RxPWDBAll = pwdb_all;
6687                 pstats->RxPower = precord_stats->RxPower =  rx_pwr_all;
6688                 pstats->RecvSignalPower = rx_pwr_all;
6689
6690                 //
6691                 // (3)EVM of HT rate
6692                 //
6693                 //if(pdrvinfo->RxHT && pdrvinfo->RxRate>=DESC90_RATEMCS8 &&
6694                  //     pdrvinfo->RxRate<=DESC90_RATEMCS15)
6695                  if(pDesc->RxHT && pDesc->RxMCS>=DESC92S_RATEMCS8 &&
6696                         pDesc->RxMCS<=DESC92S_RATEMCS15)
6697                         max_spatial_stream = 2; //both spatial stream make sense
6698                 else
6699                         max_spatial_stream = 1; //only spatial stream 1 makes sense
6700
6701                 for(i=0; i<max_spatial_stream; i++)
6702                 {
6703                         //tmp_rxevm =   pofdm_buf->rxevm_X[i];
6704                         //rx_evmX = (char)(tmp_rxevm);
6705
6706                         // Do not use shift operation like "rx_evmX >>= 1" because the compilor of free build environment
6707                         // fill most significant bit to "zero" when doing shifting operation which may change a negative
6708                         // value to positive one, then the dbm value (which is supposed to be negative)  is not correct anymore.
6709                         //rx_evmX /= 2; //dbm
6710
6711                         //evm = rtl819x_evm_dbtopercentage(rx_evmX);
6712                         evm = rtl819x_evm_dbtopercentage( (pdrvinfo->rxevm[i] /*/ 2*/));        //dbm
6713                         RT_TRACE(COMP_RF, "RXRATE=%x RXEVM=%x EVM=%s%d\n", pDesc->RxMCS, pdrvinfo->rxevm[i], "%", evm);
6714
6715                         //if(bpacket_match_bssid)
6716                         {
6717                                 if(i==0) // Fill value in RFD, Get the first spatial stream only
6718                                         pstats->SignalQuality = precord_stats->SignalQuality = (u8)(evm & 0xff);
6719                                 pstats->RxMIMOSignalQuality[i] = precord_stats->RxMIMOSignalQuality[i] = (u8)(evm & 0xff);
6720                         }
6721                 }
6722
6723
6724                 /* record rx statistics for debug */
6725                 //rxsc_sgien_exflg = pofdm_buf->rxsc_sgien_exflg;
6726                 prxsc = (phy_ofdm_rx_status_rxsc_sgien_exintfflag *)&rxsc_sgien_exflg;
6727                 //if(pdrvinfo->BW)      //40M channel
6728                 if(pDesc->BW)   //40M channel
6729                         priv->stats.received_bwtype[1+pdrvinfo->rxsc]++;
6730                 else                            //20M channel
6731                         priv->stats.received_bwtype[0]++;
6732         }
6733
6734         //UI BSS List signal strength(in percentage), make it good looking, from 0~100.
6735         //It is assigned to the BSS List in GetValueFromBeaconOrProbeRsp().
6736         if(is_cck_rate)
6737         {
6738                 pstats->SignalStrength = precord_stats->SignalStrength = (u8)(rtl819x_signal_scale_mapping((long)pwdb_all));//PWDB_ALL;//check ok
6739
6740         }
6741         else
6742         {
6743                 //pRfd->Status.SignalStrength = pRecordRfd->Status.SignalStrength = (u8)(SignalScaleMapping(total_rssi/=RF90_PATH_MAX));//(u8)(total_rssi/=RF90_PATH_MAX);
6744                 // We can judge RX path number now.
6745                 if (rf_rx_num != 0)
6746                         pstats->SignalStrength = precord_stats->SignalStrength = (u8)(rtl819x_signal_scale_mapping((long)(total_rssi/=rf_rx_num)));
6747         }
6748 }/* QueryRxPhyStatus8192S */
6749
6750 void
6751 rtl8192_record_rxdesc_forlateruse(
6752         struct ieee80211_rx_stats *     psrc_stats,
6753         struct ieee80211_rx_stats *     ptarget_stats
6754 )
6755 {
6756         ptarget_stats->bIsAMPDU = psrc_stats->bIsAMPDU;
6757         ptarget_stats->bFirstMPDU = psrc_stats->bFirstMPDU;
6758         ptarget_stats->Seq_Num = psrc_stats->Seq_Num;
6759 }
6760
6761 static void rtl8192SU_query_rxphystatus(
6762         struct r8192_priv * priv,
6763         struct ieee80211_rx_stats * pstats,
6764         rx_desc_819x_usb        *pDesc,
6765         rx_drvinfo_819x_usb  * pdrvinfo,
6766         struct ieee80211_rx_stats * precord_stats,
6767         bool bpacket_match_bssid,
6768         bool bpacket_toself,
6769         bool bPacketBeacon,
6770         bool bToSelfBA
6771         );
6772 void rtl8192SU_TranslateRxSignalStuff(struct sk_buff *skb,
6773                                    struct ieee80211_rx_stats * pstats,
6774                                    rx_desc_819x_usb     *pDesc,
6775                                    rx_drvinfo_819x_usb  *pdrvinfo)
6776 {
6777         // TODO: We must only check packet for current MAC address. Not finish
6778         rtl8192_rx_info *info = (struct rtl8192_rx_info *)skb->cb;
6779         struct net_device *dev=info->dev;
6780         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
6781         bool bpacket_match_bssid, bpacket_toself;
6782         bool bPacketBeacon=FALSE, bToSelfBA=FALSE;
6783         static struct ieee80211_rx_stats  previous_stats;
6784         struct ieee80211_hdr_3addr *hdr;//by amy
6785        u16 fc,type;
6786
6787         // Get Signal Quality for only RX data queue (but not command queue)
6788
6789         u8* tmp_buf;
6790         //u16 tmp_buf_len = 0;
6791         u8  *praddr;
6792
6793         /* Get MAC frame start address. */
6794         tmp_buf = (u8*)skb->data;// + get_rxpacket_shiftbytes_819xusb(pstats);
6795
6796         hdr = (struct ieee80211_hdr_3addr *)tmp_buf;
6797         fc = le16_to_cpu(hdr->frame_control);
6798         type = WLAN_FC_GET_TYPE(fc);
6799         praddr = hdr->addr1;
6800
6801         /* Check if the received packet is acceptabe. */
6802         bpacket_match_bssid = ((IEEE80211_FTYPE_CTL != type) &&
6803                                                         (eqMacAddr(priv->ieee80211->current_network.bssid,  (fc & IEEE80211_FCTL_TODS)? hdr->addr1 : (fc & IEEE80211_FCTL_FROMDS )? hdr->addr2 : hdr->addr3))
6804                                                                  && (!pstats->bHwError) && (!pstats->bCRC)&& (!pstats->bICV));
6805         bpacket_toself =  bpacket_match_bssid & (eqMacAddr(praddr, priv->ieee80211->dev->dev_addr));
6806
6807 #if 1//cosa
6808                 if(WLAN_FC_GET_FRAMETYPE(fc)== IEEE80211_STYPE_BEACON)
6809                 {
6810                         bPacketBeacon = true;
6811                         //DbgPrint("Beacon 2, MatchBSSID = %d, ToSelf = %d \n", bPacketMatchBSSID, bPacketToSelf);
6812                 }
6813                 if(WLAN_FC_GET_FRAMETYPE(fc) == IEEE80211_STYPE_BLOCKACK)
6814                 {
6815                         if((eqMacAddr(praddr,dev->dev_addr)))
6816                                 bToSelfBA = true;
6817                                 //DbgPrint("BlockAck, MatchBSSID = %d, ToSelf = %d \n", bPacketMatchBSSID, bPacketToSelf);
6818                 }
6819
6820 #endif
6821
6822
6823         if(bpacket_match_bssid)
6824         {
6825                 priv->stats.numpacket_matchbssid++;
6826         }
6827         if(bpacket_toself){
6828                 priv->stats.numpacket_toself++;
6829         }
6830         //
6831         // Process PHY information for previous packet (RSSI/PWDB/EVM)
6832         //
6833         // Because phy information is contained in the last packet of AMPDU only, so driver
6834         // should process phy information of previous packet
6835         rtl8192_process_phyinfo(priv, tmp_buf, &previous_stats, pstats);
6836         rtl8192SU_query_rxphystatus(priv, pstats, pDesc, pdrvinfo, &previous_stats, bpacket_match_bssid,bpacket_toself,bPacketBeacon,bToSelfBA);
6837         rtl8192_record_rxdesc_forlateruse(pstats, &previous_stats);
6838
6839 }
6840
6841 /**
6842 * Function:     UpdateReceivedRateHistogramStatistics
6843 * Overview:     Recored down the received data rate
6844 *
6845 * Input:
6846 *       struct net_device *dev
6847 *       struct ieee80211_rx_stats *stats
6848 *
6849 * Output:
6850 *
6851 *                       (priv->stats.ReceivedRateHistogram[] is updated)
6852 * Return:
6853 *               None
6854 */
6855 void
6856 UpdateReceivedRateHistogramStatistics8190(
6857         struct net_device *dev,
6858         struct ieee80211_rx_stats *stats
6859         )
6860 {
6861         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
6862         u32 rcvType=1;   //0: Total, 1:OK, 2:CRC, 3:ICV
6863         u32 rateIndex;
6864         u32 preamble_guardinterval;  //1: short preamble/GI, 0: long preamble/GI
6865
6866
6867         if(stats->bCRC)
6868         rcvType = 2;
6869         else if(stats->bICV)
6870         rcvType = 3;
6871
6872         if(stats->bShortPreamble)
6873         preamble_guardinterval = 1;// short
6874         else
6875         preamble_guardinterval = 0;// long
6876
6877         switch(stats->rate)
6878         {
6879                 //
6880                 // CCK rate
6881                 //
6882                 case MGN_1M:    rateIndex = 0;  break;
6883                 case MGN_2M:    rateIndex = 1;  break;
6884                 case MGN_5_5M:  rateIndex = 2;  break;
6885                 case MGN_11M:   rateIndex = 3;  break;
6886                 //
6887                 // Legacy OFDM rate
6888                 //
6889                 case MGN_6M:    rateIndex = 4;  break;
6890                 case MGN_9M:    rateIndex = 5;  break;
6891                 case MGN_12M:   rateIndex = 6;  break;
6892                 case MGN_18M:   rateIndex = 7;  break;
6893                 case MGN_24M:   rateIndex = 8;  break;
6894                 case MGN_36M:   rateIndex = 9;  break;
6895                 case MGN_48M:   rateIndex = 10; break;
6896                 case MGN_54M:   rateIndex = 11; break;
6897                 //
6898                 // 11n High throughput rate
6899                 //
6900                 case MGN_MCS0:  rateIndex = 12; break;
6901                 case MGN_MCS1:  rateIndex = 13; break;
6902                 case MGN_MCS2:  rateIndex = 14; break;
6903                 case MGN_MCS3:  rateIndex = 15; break;
6904                 case MGN_MCS4:  rateIndex = 16; break;
6905                 case MGN_MCS5:  rateIndex = 17; break;
6906                 case MGN_MCS6:  rateIndex = 18; break;
6907                 case MGN_MCS7:  rateIndex = 19; break;
6908                 case MGN_MCS8:  rateIndex = 20; break;
6909                 case MGN_MCS9:  rateIndex = 21; break;
6910                 case MGN_MCS10: rateIndex = 22; break;
6911                 case MGN_MCS11: rateIndex = 23; break;
6912                 case MGN_MCS12: rateIndex = 24; break;
6913                 case MGN_MCS13: rateIndex = 25; break;
6914                 case MGN_MCS14: rateIndex = 26; break;
6915                 case MGN_MCS15: rateIndex = 27; break;
6916                 default:        rateIndex = 28; break;
6917         }
6918     priv->stats.received_preamble_GI[preamble_guardinterval][rateIndex]++;
6919     priv->stats.received_rate_histogram[0][rateIndex]++; //total
6920     priv->stats.received_rate_histogram[rcvType][rateIndex]++;
6921 }
6922
6923 void rtl8192SU_query_rxdesc_status(struct sk_buff *skb, struct ieee80211_rx_stats *stats, bool bIsRxAggrSubframe)
6924 {
6925         rtl8192_rx_info *info = (struct rtl8192_rx_info *)skb->cb;
6926         struct net_device *dev=info->dev;
6927         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
6928         //rx_desc_819x_usb *desc = (rx_desc_819x_usb *)skb->data;
6929         rx_drvinfo_819x_usb  *driver_info = NULL;
6930
6931         //PRT_RFD_STATUS                                pRtRfdStatus = &pRfd->Status;
6932         //PHAL_DATA_8192SUSB                    pHalData = GET_HAL_DATA(Adapter);
6933         //pu1Byte               pDesc = (pu1Byte)pDescIn;
6934         //PRX_DRIVER_INFO_8192S         pDrvInfo;
6935
6936         rx_desc_819x_usb *desc = (rx_desc_819x_usb *)skb->data;
6937
6938         if(0)
6939         {
6940                 int m = 0;
6941                 printk("========================");
6942                 for(m=0; m<skb->len; m++){
6943                         if((m%32) == 0)
6944                                 printk("\n");
6945                         printk("%2x ",((u8*)skb->data)[m]);
6946                 }
6947                 printk("\n========================\n");
6948
6949         }
6950
6951
6952         //
6953         //Get Rx Descriptor Raw Information
6954         //
6955         stats->Length = desc->Length ;
6956         stats->RxDrvInfoSize = desc->RxDrvInfoSize*RX_DRV_INFO_SIZE_UNIT;
6957         stats->RxBufShift = (desc->Shift)&0x03;
6958         stats->bICV = desc->ICV;
6959         stats->bCRC = desc->CRC32;
6960         stats->bHwError = stats->bCRC|stats->bICV;
6961         stats->Decrypted = !desc->SWDec;//RTL8190 set this bit to indicate that Hw does not decrypt packet
6962         stats->bIsAMPDU = (desc->AMSDU==1);
6963         stats->bFirstMPDU = (desc->PAGGR==1) && (desc->FAGGR==1);
6964         stats->bShortPreamble = desc->SPLCP;
6965         stats->RxIs40MHzPacket = (desc->BW==1);
6966         stats->TimeStampLow = desc->TSFL;
6967
6968         if((desc->FAGGR==1) || (desc->PAGGR==1))
6969         {// Rx A-MPDU
6970                 RT_TRACE(COMP_RXDESC, "FirstAGGR = %d, PartAggr = %d\n", desc->FAGGR, desc->PAGGR);
6971         }
6972 //YJ,test,090310
6973 if(stats->bHwError)
6974 {
6975         if(stats->bICV)
6976                 printk("%s: Receive ICV error!!!!!!!!!!!!!!!!!!!!!!\n", __FUNCTION__);
6977         if(stats->bCRC)
6978                 printk("%s: Receive CRC error!!!!!!!!!!!!!!!!!!!!!!\n", __FUNCTION__);
6979 }
6980
6981         if(IS_UNDER_11N_AES_MODE(priv->ieee80211))
6982         {
6983                 // Always received ICV error packets in AES mode.
6984                 // This fixed HW later MIC write bug.
6985                 if(stats->bICV && !stats->bCRC)
6986                 {
6987                         stats->bICV = FALSE;
6988                         stats->bHwError = FALSE;
6989                 }
6990         }
6991
6992         // Transform HwRate to MRate
6993         if(!stats->bHwError)
6994                 //stats->DataRate = HwRateToMRate(
6995                 //      (BOOLEAN)GET_RX_DESC_RXHT(pDesc),
6996                 //      (u1Byte)GET_RX_DESC_RXMCS(pDesc),
6997                 //      (BOOLEAN)GET_RX_DESC_PAGGR(pDesc));
6998                 stats->rate = rtl8192SU_HwRateToMRate(desc->RxHT, desc->RxMCS, desc->PAGGR);
6999         else
7000                 stats->rate = MGN_1M;
7001
7002         //
7003         // Collect Rx rate/AMPDU/TSFL
7004         //
7005         //UpdateRxdRateHistogramStatistics8192S(Adapter, pRfd);
7006         //UpdateRxAMPDUHistogramStatistics8192S(Adapter, pRfd);
7007         //UpdateRxPktTimeStamp8192S(Adapter, pRfd);
7008         UpdateReceivedRateHistogramStatistics8190(dev, stats);
7009         //UpdateRxAMPDUHistogramStatistics8192S(dev, stats);    //FIXLZM
7010         UpdateRxPktTimeStamp8190(dev, stats);
7011
7012         //
7013         // Get PHY Status and RSVD parts.
7014         // <Roger_Notes> It only appears on last aggregated packet.
7015         //
7016         if (desc->PHYStatus)
7017         {
7018                 //driver_info = (rx_drvinfo_819x_usb *)(skb->data + RX_DESC_SIZE + stats->RxBufShift);
7019                 driver_info = (rx_drvinfo_819x_usb *)(skb->data + sizeof(rx_desc_819x_usb) + \
7020                                 stats->RxBufShift);
7021                 if(0)
7022                 {
7023                         int m = 0;
7024                         printk("========================\n");
7025                         printk("RX_DESC_SIZE:%d, RxBufShift:%d, RxDrvInfoSize:%d\n",
7026                                         RX_DESC_SIZE, stats->RxBufShift, stats->RxDrvInfoSize);
7027                         for(m=0; m<32; m++){
7028                                printk("%2x ",((u8*)driver_info)[m]);
7029                         }
7030                         printk("\n========================\n");
7031
7032                 }
7033
7034         }
7035
7036         //YJ,add,090107
7037         skb_pull(skb, sizeof(rx_desc_819x_usb));
7038         //YJ,add,090107,end
7039
7040         //
7041         // Get Total offset of MPDU Frame Body
7042         //
7043         if((stats->RxBufShift + stats->RxDrvInfoSize) > 0)
7044         {
7045                 stats->bShift = 1;
7046                 //YJ,add,090107
7047                 skb_pull(skb, stats->RxBufShift + stats->RxDrvInfoSize);
7048                 //YJ,add,090107,end
7049         }
7050
7051         //
7052         // Get PHY Status and RSVD parts.
7053         // <Roger_Notes> It only appears on last aggregated packet.
7054         //
7055         if (desc->PHYStatus)
7056         {
7057                 rtl8192SU_TranslateRxSignalStuff(skb, stats, desc, driver_info);
7058         }
7059 }
7060
7061 //
7062 // Description:
7063 //      The strarting address of wireless lan header will shift 1 or 2 or 3 or "more" bytes for the following reason :
7064 //      (1) QoS control : shift 2 bytes
7065 //      (2) Mesh Network : shift 1 or 3 bytes
7066 //      (3) RxDriverInfo occupies  the front parts of Rx Packets buffer(shift units is in 8Bytes)
7067 //
7068 //      It is because Lextra CPU used by 8186 or 865x series assert exception if the statrting address
7069 //      of IP header is not double word alignment.
7070 //      This features is supported in 818xb and 8190 only, but not 818x.
7071 //
7072 //      parameter: PRT_RFD, Pointer of Reeceive frame descriptor which is initialized according to
7073 //                                           Rx Descriptor
7074 //      return value: unsigned int,  number of total shifted bytes
7075 //
7076 //      Notes: 2008/06/28, created by Roger
7077 //
7078 u32 GetRxPacketShiftBytes8192SU(struct ieee80211_rx_stats  *Status, bool bIsRxAggrSubframe)
7079 {
7080         //PRT_RFD_STATUS        pRtRfdStatus = &pRfd->Status;
7081
7082         return (sizeof(rx_desc_819x_usb) + Status->RxDrvInfoSize + Status->RxBufShift);
7083 }
7084
7085 void rtl8192SU_rx_nomal(struct sk_buff* skb)
7086 {
7087         rtl8192_rx_info *info = (struct rtl8192_rx_info *)skb->cb;
7088         struct net_device *dev=info->dev;
7089         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
7090         struct ieee80211_rx_stats stats = {
7091                 .signal = 0,
7092                 .noise = -98,
7093                 .rate = 0,
7094                 //      .mac_time = jiffies,
7095                 .freq = IEEE80211_24GHZ_BAND,
7096         };
7097         u32 rx_pkt_len = 0;
7098         struct ieee80211_hdr_1addr *ieee80211_hdr = NULL;
7099         bool unicast_packet = false;
7100
7101         //printk("**********skb->len = %d\n", skb->len);
7102         /* 20 is for ps-poll */
7103         if((skb->len >=(20 + sizeof(rx_desc_819x_usb))) && (skb->len < RX_URB_SIZE)) {
7104
7105                 /* first packet should not contain Rx aggregation header */
7106                 rtl8192SU_query_rxdesc_status(skb, &stats, false);
7107                 /* TODO */
7108
7109                 /* hardware related info */
7110                 priv->stats.rxoktotal++;  //YJ,test,090108
7111
7112                 /* Process the MPDU recevied */
7113                 skb_trim(skb, skb->len - 4/*sCrcLng*/);//FIXLZM
7114
7115                 rx_pkt_len = skb->len;
7116                 ieee80211_hdr = (struct ieee80211_hdr_1addr *)skb->data;
7117                 unicast_packet = false;
7118                 if(is_broadcast_ether_addr(ieee80211_hdr->addr1)) {
7119                         //TODO
7120                 }else if(is_multicast_ether_addr(ieee80211_hdr->addr1)){
7121                         //TODO
7122                 }else {
7123                         /* unicast packet */
7124                         unicast_packet = true;
7125                 }
7126
7127                 if(!ieee80211_rtl_rx(priv->ieee80211,skb, &stats)) {
7128                         dev_kfree_skb_any(skb);
7129                 } else {
7130                 //      priv->stats.rxoktotal++;  //YJ,test,090108
7131                         if(unicast_packet) {
7132                                 priv->stats.rxbytesunicast += rx_pkt_len;
7133                         }
7134                 }
7135
7136                 //up is firs pkt, follow is next and next
7137         }
7138         else
7139         {
7140                 priv->stats.rxurberr++;
7141                 printk("actual_length:%d\n", skb->len);
7142                 dev_kfree_skb_any(skb);
7143         }
7144
7145 }
7146
7147 void
7148 rtl819xusb_process_received_packet(
7149         struct net_device *dev,
7150         struct ieee80211_rx_stats *pstats
7151         )
7152 {
7153 //      bool bfreerfd=false, bqueued=false;
7154         u8*     frame;
7155         u16     frame_len=0;
7156         struct r8192_priv *priv = ieee80211_priv(dev);
7157 //      u8                      index = 0;
7158 //      u8                      TID = 0;
7159         //u16                   seqnum = 0;
7160         //PRX_TS_RECORD pts = NULL;
7161
7162         // Get shifted bytes of Starting address of 802.11 header. 2006.09.28, by Emily
7163         //porting by amy 080508
7164         pstats->virtual_address += get_rxpacket_shiftbytes_819xusb(pstats);
7165         frame = pstats->virtual_address;
7166         frame_len = pstats->packetlength;
7167 #ifdef TODO     // by amy about HCT
7168         if(!Adapter->bInHctTest)
7169                 CountRxErrStatistics(Adapter, pRfd);
7170 #endif
7171         {
7172         #ifdef ENABLE_PS  //by amy for adding ps function in future
7173                 RT_RF_POWER_STATE rtState;
7174                 // When RF is off, we should not count the packet for hw/sw synchronize
7175                 // reason, ie. there may be a duration while sw switch is changed and hw
7176                 // switch is being changed. 2006.12.04, by shien chang.
7177                 Adapter->HalFunc.GetHwRegHandler(Adapter, HW_VAR_RF_STATE, (u8* )(&rtState));
7178                 if (rtState == eRfOff)
7179                 {
7180                         return;
7181                 }
7182         #endif
7183         priv->stats.rxframgment++;
7184
7185         }
7186 #ifdef TODO
7187         RmMonitorSignalStrength(Adapter, pRfd);
7188 #endif
7189         /* 2007/01/16 MH Add RX command packet handle here. */
7190         /* 2007/03/01 MH We have to release RFD and return if rx pkt is cmd pkt. */
7191         if (rtl819xusb_rx_command_packet(dev, pstats))
7192         {
7193                 return;
7194         }
7195
7196 #ifdef SW_CRC_CHECK
7197         SwCrcCheck();
7198 #endif
7199
7200
7201 }
7202
7203 void query_rx_cmdpkt_desc_status(struct sk_buff *skb, struct ieee80211_rx_stats *stats)
7204 {
7205 //      rtl8192_rx_info *info = (struct rtl8192_rx_info *)skb->cb;
7206 //      struct net_device *dev=info->dev;
7207 //      struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
7208         rx_desc_819x_usb *desc = (rx_desc_819x_usb *)skb->data;
7209 //      rx_drvinfo_819x_usb  *driver_info;
7210
7211         //
7212         //Get Rx Descriptor Information
7213         //
7214         stats->virtual_address = (u8*)skb->data;
7215         stats->Length = desc->Length;
7216         stats->RxDrvInfoSize = 0;
7217         stats->RxBufShift = 0;
7218         stats->packetlength = stats->Length-scrclng;
7219         stats->fraglength = stats->packetlength;
7220         stats->fragoffset = 0;
7221         stats->ntotalfrag = 1;
7222 }
7223
7224 void rtl8192SU_rx_cmd(struct sk_buff *skb)
7225 {
7226         struct rtl8192_rx_info *info = (struct rtl8192_rx_info *)skb->cb;
7227         struct net_device *dev = info->dev;
7228
7229         /* TODO */
7230         struct ieee80211_rx_stats stats = {
7231                 .signal = 0,
7232                 .noise = -98,
7233                 .rate = 0,
7234                 //      .mac_time = jiffies,
7235                 .freq = IEEE80211_24GHZ_BAND,
7236         };
7237
7238         //
7239         // Check buffer length to determine if this is a valid MPDU.
7240         //
7241         if( (skb->len >= sizeof(rx_desc_819x_usb)) && (skb->len <= RX_URB_SIZE) )//&&
7242                 //(pHalData->SwChnlInProgress == FALSE))
7243         {
7244                 //
7245                 // Collection information in Rx descriptor.
7246                 //
7247                 query_rx_cmdpkt_desc_status(skb,&stats);
7248                 // this is to be done by amy 080508     prfd->queue_id = 1;
7249
7250                 //
7251                 // Process the MPDU recevied.
7252                 //
7253                 rtl819xusb_process_received_packet(dev,&stats);
7254
7255                 dev_kfree_skb_any(skb);
7256         }
7257         else
7258         {
7259                 //RTInsertTailListWithCnt(&pAdapter->RfdIdleQueue, &pRfd->List, &pAdapter->NumIdleRfd);
7260                 //RT_ASSERT(pAdapter->NumIdleRfd <= pAdapter->NumRfd, ("HalUsbInCommandComplete8192SUsb(): Adapter->NumIdleRfd(%d)\n", pAdapter->NumIdleRfd));
7261                 //RT_TRACE(COMP_RECV, DBG_LOUD, ("HalUsbInCommandComplete8192SUsb(): NOT enough Resources!! BufLenUsed(%d), NumIdleRfd(%d)\n",
7262                         //pContext->BufLenUsed, pAdapter->NumIdleRfd));
7263         }
7264
7265         //
7266         // Reuse USB_IN_CONTEXT since we had finished processing the
7267         // buffer in USB_IN_CONTEXT.
7268         //
7269         //HalUsbReturnInContext(pAdapter, pContext);
7270
7271         //
7272         // Issue another bulk IN transfer.
7273         //
7274         //HalUsbInMpdu(pAdapter, PipeIndex);
7275
7276         RT_TRACE(COMP_RECV, "<--- HalUsbInCommandComplete8192SUsb()\n");
7277
7278 }
7279
7280 void rtl8192_irq_rx_tasklet(struct r8192_priv *priv)
7281 {
7282         struct sk_buff *skb;
7283         struct rtl8192_rx_info *info;
7284
7285         while (NULL != (skb = skb_dequeue(&priv->skb_queue))) {
7286                 info = (struct rtl8192_rx_info *)skb->cb;
7287                 switch (info->out_pipe) {
7288                 /* Nomal packet pipe */
7289                         case 3:
7290                                 //RT_TRACE(COMP_RECV, "normal in-pipe index(%d)\n",info->out_pipe);
7291                                 priv->IrpPendingCount--;
7292                                 priv->ops->rtl819x_rx_nomal(skb);
7293                                 break;
7294
7295                                 /* Command packet pipe */
7296                         case 9:
7297                                 RT_TRACE(COMP_RECV, "command in-pipe index(%d)\n",\
7298                                                 info->out_pipe);
7299                                 priv->ops->rtl819x_rx_cmd(skb);
7300                                 break;
7301
7302                         default: /* should never get here! */
7303                                 RT_TRACE(COMP_ERR, "Unknown in-pipe index(%d)\n",\
7304                                                 info->out_pipe);
7305                                 dev_kfree_skb(skb);
7306                                 break;
7307
7308                 }
7309         }
7310 }
7311
7312
7313
7314 /****************************************************************************
7315      ---------------------------- USB_STUFF---------------------------
7316 *****************************************************************************/
7317 //LZM Merge from windows HalUsbSetQueuePipeMapping8192SUsb 090319
7318 static void HalUsbSetQueuePipeMapping8192SUsb(struct usb_interface *intf, struct net_device *dev)
7319 {
7320         struct r8192_priv *priv = ieee80211_priv(dev);
7321         struct usb_host_interface *iface_desc;
7322         struct usb_endpoint_descriptor *endpoint;
7323         u8 i = 0;
7324
7325         priv->ep_in_num = 0;
7326         priv->ep_out_num = 0;
7327         memset(priv->RtOutPipes,0,16);
7328         memset(priv->RtInPipes,0,16);
7329
7330         iface_desc = intf->cur_altsetting;
7331         priv->ep_num = iface_desc->desc.bNumEndpoints;
7332
7333         for (i = 0; i < priv->ep_num; ++i) {
7334                 endpoint = &iface_desc->endpoint[i].desc;
7335                 if (usb_endpoint_is_bulk_in(endpoint)) {
7336                         priv->RtInPipes[priv->ep_in_num] = usb_endpoint_num(endpoint);
7337                         priv->ep_in_num ++;
7338                         //printk("in_endpoint_idx = %d\n", usb_endpoint_num(endpoint));
7339                 } else if (usb_endpoint_is_bulk_out(endpoint)) {
7340                         priv->RtOutPipes[priv->ep_out_num] = usb_endpoint_num(endpoint);
7341                         priv->ep_out_num ++;
7342                         //printk("out_endpoint_idx = %d\n", usb_endpoint_num(endpoint));
7343                 }
7344         }
7345         {
7346                 memset(priv->txqueue_to_outpipemap,0,9);
7347                 if (priv->ep_num == 6) {
7348                         // BK, BE, VI, VO, HCCA, TXCMD, MGNT, HIGH, BEACON
7349                         u8 queuetopipe[] = {3, 2, 1, 0, 4, 4, 4, 4, 4};
7350
7351                         memcpy(priv->txqueue_to_outpipemap,queuetopipe,9);
7352                 } else if (priv->ep_num == 4) {
7353                         // BK, BE, VI, VO, HCCA, TXCMD, MGNT, HIGH, BEACON
7354                         u8 queuetopipe[] = {1, 1, 0, 0, 2, 2, 2, 2, 2};
7355
7356                         memcpy(priv->txqueue_to_outpipemap,queuetopipe,9);
7357                 } else if (priv->ep_num > 9) {
7358                         // BK, BE, VI, VO, HCCA, TXCMD, MGNT, HIGH, BEACON
7359                         u8 queuetopipe[] = {3, 2, 1, 0, 4, 8, 7, 6, 5};
7360
7361                         memcpy(priv->txqueue_to_outpipemap,queuetopipe,9);
7362                 } else {//use sigle pipe
7363                         // BK, BE, VI, VO, HCCA, TXCMD, MGNT, HIGH, BEACON
7364                         u8 queuetopipe[] = {0, 0, 0, 0, 0, 0, 0, 0, 0};
7365                         memcpy(priv->txqueue_to_outpipemap,queuetopipe,9);
7366                 }
7367         }
7368         printk("==>ep_num:%d, in_ep_num:%d, out_ep_num:%d\n", priv->ep_num, priv->ep_in_num, priv->ep_out_num);
7369
7370         printk("==>RtInPipes:");
7371         for(i=0; i < priv->ep_in_num; i++)
7372                 printk("%d  ", priv->RtInPipes[i]);
7373         printk("\n");
7374
7375         printk("==>RtOutPipes:");
7376         for(i=0; i < priv->ep_out_num; i++)
7377                 printk("%d  ", priv->RtOutPipes[i]);
7378         printk("\n");
7379
7380         printk("==>txqueue_to_outpipemap for BK, BE, VI, VO, HCCA, TXCMD, MGNT, HIGH, BEACON:\n");
7381         for(i=0; i < 9; i++)
7382                 printk("%d  ", priv->txqueue_to_outpipemap[i]);
7383         printk("\n");
7384
7385         return;
7386 }
7387
7388 static const struct net_device_ops rtl8192_netdev_ops = {
7389         .ndo_open               = rtl8192_open,
7390         .ndo_stop               = rtl8192_close,
7391         .ndo_get_stats          = rtl8192_stats,
7392         .ndo_tx_timeout         = tx_timeout,
7393         .ndo_do_ioctl           = rtl8192_ioctl,
7394         .ndo_set_multicast_list = r8192_set_multicast,
7395         .ndo_set_mac_address    = r8192_set_mac_adr,
7396         .ndo_validate_addr      = eth_validate_addr,
7397         .ndo_change_mtu         = eth_change_mtu,
7398         .ndo_start_xmit         = rtl8192_ieee80211_rtl_xmit,
7399 };
7400
7401 static int __devinit rtl8192_usb_probe(struct usb_interface *intf,
7402                          const struct usb_device_id *id)
7403 {
7404 //      unsigned long ioaddr = 0;
7405         struct net_device *dev = NULL;
7406         struct r8192_priv *priv= NULL;
7407         struct usb_device *udev = interface_to_usbdev(intf);
7408
7409         RT_TRACE(COMP_INIT, "Oops: i'm coming\n");
7410
7411         dev = alloc_ieee80211(sizeof(struct r8192_priv));
7412
7413         usb_set_intfdata(intf, dev);
7414         SET_NETDEV_DEV(dev, &intf->dev);
7415         priv = ieee80211_priv(dev);
7416         priv->ieee80211 = netdev_priv(dev);
7417         priv->udev=udev;
7418
7419         HalUsbSetQueuePipeMapping8192SUsb(intf, dev);
7420
7421         //printk("===============>NIC 8192SU\n");
7422         priv->ops = &rtl8192su_ops;
7423
7424         dev->netdev_ops = &rtl8192_netdev_ops;
7425
7426          //DMESG("Oops: i'm coming\n");
7427         dev->wireless_handlers = (struct iw_handler_def *) &r8192_wx_handlers_def;
7428
7429         dev->type=ARPHRD_ETHER;
7430
7431         dev->watchdog_timeo = HZ*3;     //modified by john, 0805
7432
7433         if (dev_alloc_name(dev, ifname) < 0){
7434                 RT_TRACE(COMP_INIT, "Oops: devname already taken! Trying wlan%%d...\n");
7435                 ifname = "wlan%d";
7436                 dev_alloc_name(dev, ifname);
7437         }
7438
7439         RT_TRACE(COMP_INIT, "Driver probe completed1\n");
7440 #if 1
7441         if(rtl8192_init(dev)!=0){
7442                 RT_TRACE(COMP_ERR, "Initialization failed");
7443                 goto fail;
7444         }
7445 #endif
7446         netif_carrier_off(dev);
7447         netif_stop_queue(dev);
7448
7449         register_netdev(dev);
7450         RT_TRACE(COMP_INIT, "dev name=======> %s\n",dev->name);
7451         rtl8192_proc_init_one(dev);
7452
7453
7454         RT_TRACE(COMP_INIT, "Driver probe completed\n");
7455         return 0;
7456 fail:
7457         free_ieee80211(dev);
7458
7459         RT_TRACE(COMP_ERR, "wlan driver load failed\n");
7460         return -ENODEV;
7461 }
7462
7463 //detach all the work and timer structure declared or inititialize in r8192U_init function.
7464 void rtl8192_cancel_deferred_work(struct r8192_priv* priv)
7465 {
7466         cancel_work_sync(&priv->reset_wq);
7467         cancel_work_sync(&priv->qos_activate);
7468         cancel_delayed_work(&priv->watch_dog_wq);
7469         cancel_delayed_work(&priv->update_beacon_wq);
7470         cancel_delayed_work(&priv->ieee80211->hw_wakeup_wq);
7471         cancel_delayed_work(&priv->ieee80211->hw_sleep_wq);
7472         //cancel_work_sync(&priv->SetBWModeWorkItem);
7473         //cancel_work_sync(&priv->SwChnlWorkItem);
7474 }
7475
7476 static void __devexit rtl8192_usb_disconnect(struct usb_interface *intf)
7477 {
7478         struct net_device *dev = usb_get_intfdata(intf);
7479         struct r8192_priv *priv = ieee80211_priv(dev);
7480         if(dev){
7481
7482                 unregister_netdev(dev);
7483
7484                 RT_TRACE(COMP_DOWN, "=============>wlan driver to be removed\n");
7485                 rtl8192_proc_remove_one(dev);
7486
7487                         rtl8192_down(dev);
7488                 if (priv->pFirmware)
7489                 {
7490                         vfree(priv->pFirmware);
7491                         priv->pFirmware = NULL;
7492                 }
7493         //      priv->rf_close(dev);
7494 //              rtl8192_SetRFPowerState(dev, eRfOff);
7495                 destroy_workqueue(priv->priv_wq);
7496                 //rtl8192_irq_disable(dev);
7497                 //rtl8192_reset(dev);
7498                 mdelay(10);
7499
7500         }
7501         free_ieee80211(dev);
7502         RT_TRACE(COMP_DOWN, "wlan driver removed\n");
7503 }
7504
7505 /* fun with the built-in ieee80211 stack... */
7506 extern int ieee80211_debug_init(void);
7507 extern void ieee80211_debug_exit(void);
7508 extern int ieee80211_crypto_init(void);
7509 extern void ieee80211_crypto_deinit(void);
7510 extern int ieee80211_crypto_tkip_init(void);
7511 extern void ieee80211_crypto_tkip_exit(void);
7512 extern int ieee80211_crypto_ccmp_init(void);
7513 extern void ieee80211_crypto_ccmp_exit(void);
7514 extern int ieee80211_crypto_wep_init(void);
7515 extern void ieee80211_crypto_wep_exit(void);
7516
7517 static int __init rtl8192_usb_module_init(void)
7518 {
7519         int ret;
7520
7521 #ifdef CONFIG_IEEE80211_DEBUG
7522         ret = ieee80211_debug_init();
7523         if (ret) {
7524                 printk(KERN_ERR "ieee80211_debug_init() failed %d\n", ret);
7525                 return ret;
7526         }
7527 #endif
7528         ret = ieee80211_crypto_init();
7529         if (ret) {
7530                 printk(KERN_ERR "ieee80211_crypto_init() failed %d\n", ret);
7531                 return ret;
7532         }
7533
7534         ret = ieee80211_crypto_tkip_init();
7535         if (ret) {
7536                 printk(KERN_ERR "ieee80211_crypto_tkip_init() failed %d\n",
7537                         ret);
7538                 return ret;
7539         }
7540
7541         ret = ieee80211_crypto_ccmp_init();
7542         if (ret) {
7543                 printk(KERN_ERR "ieee80211_crypto_ccmp_init() failed %d\n",
7544                         ret);
7545                 return ret;
7546         }
7547
7548         ret = ieee80211_crypto_wep_init();
7549         if (ret) {
7550                 printk(KERN_ERR "ieee80211_crypto_wep_init() failed %d\n", ret);
7551                 return ret;
7552         }
7553
7554         printk(KERN_INFO "\nLinux kernel driver for RTL8192 based WLAN cards\n");
7555         printk(KERN_INFO "Copyright (c) 2007-2008, Realsil Wlan\n");
7556         RT_TRACE(COMP_INIT, "Initializing module");
7557         RT_TRACE(COMP_INIT, "Wireless extensions version %d", WIRELESS_EXT);
7558         rtl8192_proc_module_init();
7559         return usb_register(&rtl8192_usb_driver);
7560 }
7561
7562
7563 static void __exit rtl8192_usb_module_exit(void)
7564 {
7565         usb_deregister(&rtl8192_usb_driver);
7566
7567         RT_TRACE(COMP_DOWN, "Exiting");
7568         rtl8192_proc_module_remove();
7569
7570         ieee80211_crypto_tkip_exit();
7571         ieee80211_crypto_ccmp_exit();
7572         ieee80211_crypto_wep_exit();
7573         ieee80211_crypto_deinit();
7574 #ifdef CONFIG_IEEE80211_DEBUG
7575         ieee80211_debug_exit();
7576 #endif
7577 }
7578
7579
7580 void rtl8192_try_wake_queue(struct net_device *dev, int pri)
7581 {
7582         unsigned long flags;
7583         short enough_desc;
7584         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
7585
7586         spin_lock_irqsave(&priv->tx_lock,flags);
7587         enough_desc = check_nic_enough_desc(dev,pri);
7588         spin_unlock_irqrestore(&priv->tx_lock,flags);
7589
7590         if(enough_desc)
7591                 ieee80211_rtl_wake_queue(priv->ieee80211);
7592 }
7593
7594 void EnableHWSecurityConfig8192(struct net_device *dev)
7595 {
7596         u8 SECR_value = 0x0;
7597         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
7598          struct ieee80211_device* ieee = priv->ieee80211;
7599
7600         SECR_value = SCR_TxEncEnable | SCR_RxDecEnable;
7601 #if 1
7602         if (((KEY_TYPE_WEP40 == ieee->pairwise_key_type) || (KEY_TYPE_WEP104 == ieee->pairwise_key_type)) && (priv->ieee80211->auth_mode != 2))
7603         {
7604                 SECR_value |= SCR_RxUseDK;
7605                 SECR_value |= SCR_TxUseDK;
7606         }
7607         else if ((ieee->iw_mode == IW_MODE_ADHOC) && (ieee->pairwise_key_type & (KEY_TYPE_CCMP | KEY_TYPE_TKIP)))
7608         {
7609                 SECR_value |= SCR_RxUseDK;
7610                 SECR_value |= SCR_TxUseDK;
7611         }
7612 #endif
7613         //add HWSec active enable here.
7614 //default using hwsec. when peer AP is in N mode only and pairwise_key_type is none_aes(which HT_IOT_ACT_PURE_N_MODE indicates it), use software security. when peer AP is in b,g,n mode mixed and pairwise_key_type is none_aes, use g mode hw security. WB on 2008.7.4
7615
7616         ieee->hwsec_active = 1;
7617
7618         if ((ieee->pHTInfo->IOTAction&HT_IOT_ACT_PURE_N_MODE) || !hwwep)//!ieee->hwsec_support) //add hwsec_support flag to totol control hw_sec on/off
7619         {
7620                 ieee->hwsec_active = 0;
7621                 SECR_value &= ~SCR_RxDecEnable;
7622         }
7623
7624         RT_TRACE(COMP_SEC,"%s:, hwsec:%d, pairwise_key:%d, SECR_value:%x\n", __FUNCTION__, \
7625                         ieee->hwsec_active, ieee->pairwise_key_type, SECR_value);
7626         {
7627                 write_nic_byte(dev, SECR,  SECR_value);//SECR_value |  SCR_UseDK );
7628         }
7629 }
7630
7631
7632 void setKey(    struct net_device *dev,
7633                 u8 EntryNo,
7634                 u8 KeyIndex,
7635                 u16 KeyType,
7636                 u8 *MacAddr,
7637                 u8 DefaultKey,
7638                 u32 *KeyContent )
7639 {
7640         u32 TargetCommand = 0;
7641         u32 TargetContent = 0;
7642         u16 usConfig = 0;
7643         u8 i;
7644         if (EntryNo >= TOTAL_CAM_ENTRY)
7645                 RT_TRACE(COMP_ERR, "cam entry exceeds in setKey()\n");
7646
7647         RT_TRACE(COMP_SEC, "====>to setKey(), dev:%p, EntryNo:%d, KeyIndex:%d, KeyType:%d, MacAddr%pM\n", dev,EntryNo, KeyIndex, KeyType, MacAddr);
7648
7649         if (DefaultKey)
7650                 usConfig |= BIT15 | (KeyType<<2);
7651         else
7652                 usConfig |= BIT15 | (KeyType<<2) | KeyIndex;
7653 //      usConfig |= BIT15 | (KeyType<<2) | (DefaultKey<<5) | KeyIndex;
7654
7655
7656         for(i=0 ; i<CAM_CONTENT_COUNT; i++){
7657                 TargetCommand  = i+CAM_CONTENT_COUNT*EntryNo;
7658                 TargetCommand |= BIT31|BIT16;
7659
7660                 if(i==0){//MAC|Config
7661                         TargetContent = (u32)(*(MacAddr+0)) << 16|
7662                                         (u32)(*(MacAddr+1)) << 24|
7663                                         (u32)usConfig;
7664
7665                         write_nic_dword(dev, WCAMI, TargetContent);
7666                         write_nic_dword(dev, RWCAM, TargetCommand);
7667         //              printk("setkey cam =%8x\n", read_cam(dev, i+6*EntryNo));
7668                 }
7669                 else if(i==1){//MAC
7670                         TargetContent = (u32)(*(MacAddr+2))      |
7671                                         (u32)(*(MacAddr+3)) <<  8|
7672                                         (u32)(*(MacAddr+4)) << 16|
7673                                         (u32)(*(MacAddr+5)) << 24;
7674                         write_nic_dword(dev, WCAMI, TargetContent);
7675                         write_nic_dword(dev, RWCAM, TargetCommand);
7676                 }
7677                 else {
7678                         //Key Material
7679                         if(KeyContent !=NULL){
7680                         write_nic_dword(dev, WCAMI, (u32)(*(KeyContent+i-2)) );
7681                         write_nic_dword(dev, RWCAM, TargetCommand);
7682                 }
7683         }
7684         }
7685
7686 }
7687
7688 /***************************************************************************
7689      ------------------- module init / exit stubs ----------------
7690 ****************************************************************************/
7691 module_init(rtl8192_usb_module_init);
7692 module_exit(rtl8192_usb_module_exit);