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