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