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