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