]> git.karo-electronics.de Git - mv-sheeva.git/blob - drivers/staging/rtl8192su/r8192U_core.c
eb5f9011f10d44066518fb1dbb1963c70df9c268
[mv-sheeva.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 #ifndef CONFIG_FORCE_HARD_FLOAT
28 double __floatsidf (int i) { return i; }
29 unsigned int __fixunsdfsi (double d) { return d; }
30 double __adddf3(double a, double b) { return a+b; }
31 double __addsf3(float a, float b) { return a+b; }
32 double __subdf3(double a, double b) { return a-b; }
33 double __extendsfdf2(float a) {return a;}
34 #endif
35
36 #undef LOOP_TEST
37 #undef DUMP_RX
38 #undef DUMP_TX
39 #undef DEBUG_TX_DESC2
40 #undef RX_DONT_PASS_UL
41 #undef DEBUG_EPROM
42 #undef DEBUG_RX_VERBOSE
43 #undef DUMMY_RX
44 #undef DEBUG_ZERO_RX
45 #undef DEBUG_RX_SKB
46 #undef DEBUG_TX_FRAG
47 #undef DEBUG_RX_FRAG
48 #undef DEBUG_TX_FILLDESC
49 #undef DEBUG_TX
50 #undef DEBUG_IRQ
51 #undef DEBUG_RX
52 #undef DEBUG_RXALLOC
53 #undef DEBUG_REGISTERS
54 #undef DEBUG_RING
55 #undef DEBUG_IRQ_TASKLET
56 #undef DEBUG_TX_ALLOC
57 #undef DEBUG_TX_DESC
58
59 #define CONFIG_RTL8192_IO_MAP
60
61 #ifdef RTL8192SU
62 #include <asm/uaccess.h>
63 #include "r8192U.h"
64 //#include "r8190_rtl8256.h" /* RTL8225 Radio frontend */
65 #include "r8180_93cx6.h"   /* Card EEPROM */
66 #include "r8192U_wx.h"
67
68 #include "r8192S_rtl8225.h"
69 #include "r8192S_hw.h"
70 #include "r8192S_phy.h"
71 #include "r8192S_phyreg.h"
72 #include "r8192S_Efuse.h"
73
74 #include "r819xU_cmdpkt.h"
75 #include "r8192U_dm.h"
76 //#include "r8192xU_phyreg.h"
77 #include <linux/usb.h>
78
79 #include "r8192U_pm.h"
80
81 #include "ieee80211/dot11d.h"
82
83 #else
84
85 #include <asm/uaccess.h>
86 #include "r8192U_hw.h"
87 #include "r8192U.h"
88 #include "r8190_rtl8256.h" /* RTL8225 Radio frontend */
89 #include "r8180_93cx6.h"   /* Card EEPROM */
90 #include "r8192U_wx.h"
91 #include "r819xU_phy.h" //added by WB 4.30.2008
92 #include "r819xU_phyreg.h"
93 #include "r819xU_cmdpkt.h"
94 #include "r8192U_dm.h"
95 //#include "r8192xU_phyreg.h"
96 #include <linux/usb.h>
97
98 #include "r8192U_pm.h"
99
100 #include "ieee80211/dot11d.h"
101
102 #endif
103
104
105 #ifdef RTL8192SU
106 u32 rt_global_debug_component = \
107 //                              COMP_TRACE      |
108 //                              COMP_DBG        |
109 //                              COMP_INIT       |
110 //                              COMP_RECV       |
111 //                              COMP_SEND       |
112 //                              COMP_IO         |
113                                 COMP_POWER      |
114 //                              COMP_EPROM      |
115                                 COMP_SWBW       |
116                                 COMP_POWER_TRACKING |
117                                 COMP_TURBO      |
118                                 COMP_QOS        |
119 //                              COMP_RATE       |
120 //                              COMP_RM         |
121                                 COMP_DIG        |
122 //                              COMP_EFUSE      |
123 //                              COMP_CH         |
124 //                              COMP_TXAGC      |
125                                 COMP_HIPWR      |
126 //                              COMP_HALDM      |
127                                 COMP_SEC        |
128                                 COMP_LED        |
129 //                              COMP_RF         |
130 //                              COMP_RXDESC     |
131                                 COMP_FIRMWARE   |
132                                 COMP_HT         |
133                                 COMP_AMSDU      |
134                                 COMP_SCAN       |
135 //                              COMP_CMD        |
136                                 COMP_DOWN       |
137                                 COMP_RESET      |
138                                 COMP_ERR; //always open err flags on
139 #else
140 //set here to open your trace code. //WB
141 u32 rt_global_debug_component = \
142                         //      COMP_INIT       |
143 //                              COMP_DBG        |
144                         //      COMP_EPROM      |
145 //                              COMP_PHY        |
146                         //      COMP_RF         |
147 //                              COMP_FIRMWARE   |
148 //                              COMP_CH         |
149                         //      COMP_POWER_TRACKING |
150 //                              COMP_RATE       |
151                         //      COMP_TXAGC      |
152                 //              COMP_TRACE      |
153                                 COMP_DOWN       |
154                 //              COMP_RECV       |
155                 //              COMP_SWBW       |
156                                 COMP_SEC        |
157         //                      COMP_RESET      |
158                 //              COMP_SEND       |
159                         //      COMP_EVENTS     |
160                                 COMP_ERR ; //always open err flags on
161 #endif
162
163 #define TOTAL_CAM_ENTRY 32
164 #define CAM_CONTENT_COUNT 8
165
166 static struct usb_device_id rtl8192_usb_id_tbl[] = {
167         /* Realtek */
168         {USB_DEVICE(0x0bda, 0x8192)},
169         {USB_DEVICE(0x0bda, 0x8709)},
170         /* Corega */
171         {USB_DEVICE(0x07aa, 0x0043)},
172         /* Belkin */
173         {USB_DEVICE(0x050d, 0x805E)},
174         /* Sitecom */
175         {USB_DEVICE(0x0df6, 0x0031)},
176         /* EnGenius */
177         {USB_DEVICE(0x1740, 0x9201)},
178         /* Dlink */
179         {USB_DEVICE(0x2001, 0x3301)},
180         /* Zinwell */
181         {USB_DEVICE(0x5a57, 0x0290)},
182         //92SU
183         {USB_DEVICE(0x0bda, 0x8172)},
184         {}
185 };
186
187 MODULE_LICENSE("GPL");
188 MODULE_VERSION("V 1.1");
189 MODULE_DEVICE_TABLE(usb, rtl8192_usb_id_tbl);
190 MODULE_DESCRIPTION("Linux driver for Realtek RTL8192 USB WiFi cards");
191
192 static char* ifname = "wlan%d";
193 #if 0
194 static int hwseqnum = 0;
195 static int hwwep = 0;
196 #endif
197 static int hwwep = 1;  //default use hw. set 0 to use software security
198 static int channels = 0x3fff;
199
200
201
202 module_param(ifname, charp, S_IRUGO|S_IWUSR );
203 //module_param(hwseqnum,int, S_IRUGO|S_IWUSR);
204 module_param(hwwep,int, S_IRUGO|S_IWUSR);
205 module_param(channels,int, S_IRUGO|S_IWUSR);
206
207 MODULE_PARM_DESC(ifname," Net interface name, wlan%d=default");
208 //MODULE_PARM_DESC(hwseqnum," Try to use hardware 802.11 header sequence numbers. Zero=default");
209 MODULE_PARM_DESC(hwwep," Try to use hardware security support. ");
210 MODULE_PARM_DESC(channels," Channel bitmask for specific locales. NYI");
211
212 static int __devinit rtl8192_usb_probe(struct usb_interface *intf,
213                          const struct usb_device_id *id);
214 static void __devexit rtl8192_usb_disconnect(struct usb_interface *intf);
215
216 static struct usb_driver rtl8192_usb_driver = {
217         .name           = RTL819xU_MODULE_NAME,           /* Driver name   */
218         .id_table       = rtl8192_usb_id_tbl,             /* PCI_ID table  */
219         .probe          = rtl8192_usb_probe,              /* probe fn      */
220         .disconnect     = rtl8192_usb_disconnect,         /* remove fn     */
221         .suspend        = rtl8192U_suspend,               /* PM suspend fn */
222         .resume         = rtl8192U_resume,                 /* PM resume fn  */
223         .reset_resume   = rtl8192U_resume,                 /* PM reset resume fn  */
224 };
225
226
227 #ifdef RTL8192SU
228 static void     rtl8192SU_read_eeprom_info(struct net_device *dev);
229 short   rtl8192SU_tx(struct net_device *dev, struct sk_buff* skb);
230 void    rtl8192SU_rx_nomal(struct sk_buff* skb);
231 void    rtl8192SU_rx_cmd(struct sk_buff *skb);
232 bool    rtl8192SU_adapter_start(struct net_device *dev);
233 short   rtl8192SU_tx_cmd(struct net_device *dev, struct sk_buff *skb);
234 void    rtl8192SU_link_change(struct net_device *dev);
235 void    InitialGain8192S(struct net_device *dev,u8 Operation);
236 void    rtl8192SU_query_rxdesc_status(struct sk_buff *skb, struct ieee80211_rx_stats *stats, bool bIsRxAggrSubframe);
237
238 struct rtl819x_ops rtl8192su_ops = {
239         .nic_type = NIC_8192SU,
240         .rtl819x_read_eeprom_info = rtl8192SU_read_eeprom_info,
241         .rtl819x_tx = rtl8192SU_tx,
242         .rtl819x_tx_cmd = rtl8192SU_tx_cmd,
243         .rtl819x_rx_nomal = rtl8192SU_rx_nomal,
244         .rtl819x_rx_cmd = rtl8192SU_rx_cmd,
245         .rtl819x_adapter_start = rtl8192SU_adapter_start,
246         .rtl819x_link_change = rtl8192SU_link_change,
247         .rtl819x_initial_gain = InitialGain8192S,
248         .rtl819x_query_rxdesc_status = rtl8192SU_query_rxdesc_status,
249 };
250 #else
251 static void     rtl8192_read_eeprom_info(struct net_device *dev);
252 short   rtl8192_tx(struct net_device *dev, struct sk_buff* skb);
253 void    rtl8192_rx_nomal(struct sk_buff* skb);
254 void    rtl8192_rx_cmd(struct sk_buff *skb);
255 bool    rtl8192_adapter_start(struct net_device *dev);
256 short   rtl819xU_tx_cmd(struct net_device *dev, struct sk_buff *skb);
257 void    rtl8192_link_change(struct net_device *dev);
258 void    InitialGain819xUsb(struct net_device *dev,u8 Operation);
259 void    query_rxdesc_status(struct sk_buff *skb, struct ieee80211_rx_stats *stats, bool bIsRxAggrSubframe);
260
261 struct rtl819x_ops rtl8192u_ops = {
262         .nic_type = NIC_8192U,
263         .rtl819x_read_eeprom_info = rtl8192_read_eeprom_info,
264         .rtl819x_tx = rtl8192_tx,
265         .rtl819x_tx_cmd = rtl819xU_tx_cmd,
266         .rtl819x_rx_nomal = rtl8192_rx_nomal,
267         .rtl819x_rx_cmd = rtl8192_rx_cmd,
268         .rtl819x_adapter_start = rtl8192_adapter_start,
269         .rtl819x_link_change = rtl8192_link_change,
270         .rtl819x_initial_gain = InitialGain819xUsb,
271         .rtl819x_query_rxdesc_status = query_rxdesc_status,
272 };
273 #endif
274
275
276 typedef struct _CHANNEL_LIST
277 {
278         u8      Channel[32];
279         u8      Len;
280 }CHANNEL_LIST, *PCHANNEL_LIST;
281
282 static CHANNEL_LIST ChannelPlan[] = {
283         {{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
284         {{1,2,3,4,5,6,7,8,9,10,11},11},                                                 //IC
285         {{1,2,3,4,5,6,7,8,9,10,11,12,13,36,40,44,48,52,56,60,64},21},   //ETSI
286         {{1,2,3,4,5,6,7,8,9,10,11,12,13},13},    //Spain. Change to ETSI.
287         {{1,2,3,4,5,6,7,8,9,10,11,12,13},13},   //France. Change to ETSI.
288         {{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
289         {{1,2,3,4,5,6,7,8,9,10,11,12,13,14,36,40,44,48,52,56,60,64},22},//MKK1
290         {{1,2,3,4,5,6,7,8,9,10,11,12,13},13},   //Israel.
291         {{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
292         {{1,2,3,4,5,6,7,8,9,10,11,12,13,14,36,40,44,48,52,56,60,64}, 22},    //MIC
293         {{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
294 };
295
296 static void rtl819x_set_channel_map(u8 channel_plan, struct r8192_priv* priv)
297 {
298         int i, max_chan=-1, min_chan=-1;
299         struct ieee80211_device* ieee = priv->ieee80211;
300         switch (channel_plan)
301         {
302                 case COUNTRY_CODE_FCC:
303                 case COUNTRY_CODE_IC:
304                 case COUNTRY_CODE_ETSI:
305                 case COUNTRY_CODE_SPAIN:
306                 case COUNTRY_CODE_FRANCE:
307                 case COUNTRY_CODE_MKK:
308                 case COUNTRY_CODE_MKK1:
309                 case COUNTRY_CODE_ISRAEL:
310                 case COUNTRY_CODE_TELEC:
311                 case COUNTRY_CODE_MIC:
312                 {
313                         Dot11d_Init(ieee);
314                         ieee->bGlobalDomain = false;
315                         //acturally 8225 & 8256 rf chip only support B,G,24N mode
316                         if ((priv->rf_chip == RF_8225) || (priv->rf_chip == RF_8256) || (priv->rf_chip == RF_6052))
317                         {
318                                 min_chan = 1;
319                                 max_chan = 14;
320                         }
321                         else
322                         {
323                                 RT_TRACE(COMP_ERR, "unknown rf chip, can't set channel map in function:%s()\n", __FUNCTION__);
324                         }
325                         if (ChannelPlan[channel_plan].Len != 0){
326                                 // Clear old channel map
327                                 memset(GET_DOT11D_INFO(ieee)->channel_map, 0, sizeof(GET_DOT11D_INFO(ieee)->channel_map));
328                                 // Set new channel map
329                                 for (i=0;i<ChannelPlan[channel_plan].Len;i++)
330                                 {
331                                         if (ChannelPlan[channel_plan].Channel[i] < min_chan || ChannelPlan[channel_plan].Channel[i] > max_chan)
332                                         break;
333                                         GET_DOT11D_INFO(ieee)->channel_map[ChannelPlan[channel_plan].Channel[i]] = 1;
334                                 }
335                         }
336                         break;
337                 }
338                 case COUNTRY_CODE_GLOBAL_DOMAIN:
339                 {
340                         GET_DOT11D_INFO(ieee)->bEnabled = 0;//this flag enabled to follow 11d country IE setting, otherwise, it shall follow global domain settings.
341                         Dot11d_Reset(ieee);
342                         ieee->bGlobalDomain = true;
343                         break;
344                 }
345                 default:
346                         break;
347         }
348         return;
349 }
350
351 #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 )
352
353 #ifdef RTL8192SU
354 #define         rx_hal_is_cck_rate(_pDesc)\
355                         ((_pDesc->RxMCS  == DESC92S_RATE1M ||\
356                         _pDesc->RxMCS == DESC92S_RATE2M ||\
357                         _pDesc->RxMCS == DESC92S_RATE5_5M ||\
358                         _pDesc->RxMCS == DESC92S_RATE11M) &&\
359                         !_pDesc->RxHT)
360
361 #define         tx_hal_is_cck_rate(_DataRate)\
362                         ( _DataRate == MGN_1M ||\
363                          _DataRate == MGN_2M ||\
364                          _DataRate == MGN_5_5M ||\
365                          _DataRate == MGN_11M )
366
367 #else
368 #define         rx_hal_is_cck_rate(_pdrvinfo)\
369                         ((_pdrvinfo->RxRate == DESC90_RATE1M ||\
370                         _pdrvinfo->RxRate == DESC90_RATE2M ||\
371                         _pdrvinfo->RxRate == DESC90_RATE5_5M ||\
372                         _pdrvinfo->RxRate == DESC90_RATE11M) &&\
373                         !_pdrvinfo->RxHT)
374 #endif
375
376
377
378 void CamResetAllEntry(struct net_device *dev)
379 {
380 #if 1
381         u32 ulcommand = 0;
382         //2004/02/11  In static WEP, OID_ADD_KEY or OID_ADD_WEP are set before STA associate to AP.
383         // However, ResetKey is called on OID_802_11_INFRASTRUCTURE_MODE and MlmeAssociateRequest
384         // In this condition, Cam can not be reset because upper layer will not set this static key again.
385         //if(Adapter->EncAlgorithm == WEP_Encryption)
386         //      return;
387 //debug
388         //DbgPrint("========================================\n");
389         //DbgPrint("                            Call ResetAllEntry                                              \n");
390         //DbgPrint("========================================\n\n");
391         ulcommand |= BIT31|BIT30;
392         write_nic_dword(dev, RWCAM, ulcommand);
393 #else
394         for(ucIndex=0;ucIndex<TOTAL_CAM_ENTRY;ucIndex++)
395                 CAM_mark_invalid(dev, ucIndex);
396         for(ucIndex=0;ucIndex<TOTAL_CAM_ENTRY;ucIndex++)
397                 CAM_empty_entry(dev, ucIndex);
398 #endif
399
400 }
401
402
403 void write_cam(struct net_device *dev, u8 addr, u32 data)
404 {
405         write_nic_dword(dev, WCAMI, data);
406         write_nic_dword(dev, RWCAM, BIT31|BIT16|(addr&0xff) );
407 }
408
409 u32 read_cam(struct net_device *dev, u8 addr)
410 {
411         write_nic_dword(dev, RWCAM, 0x80000000|(addr&0xff) );
412         return read_nic_dword(dev, 0xa8);
413 }
414
415 void write_nic_byte_E(struct net_device *dev, int indx, u8 data)
416 {
417         int status;
418         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
419         struct usb_device *udev = priv->udev;
420
421         status = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
422                                RTL8187_REQ_SET_REGS, RTL8187_REQT_WRITE,
423                                indx|0xfe00, 0, &data, 1, HZ / 2);
424
425         if (status < 0)
426         {
427                 printk("write_nic_byte_E TimeOut! status:%d\n", status);
428         }
429 }
430
431 u8 read_nic_byte_E(struct net_device *dev, int indx)
432 {
433         int status;
434         u8 data;
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|0xfe00, 0, &data, 1, HZ / 2);
441
442         if (status < 0)
443         {
444                 printk("read_nic_byte_E TimeOut! status:%d\n", status);
445         }
446
447         return data;
448 }
449 //as 92U has extend page from 4 to 16, so modify functions below.
450 void write_nic_byte(struct net_device *dev, int indx, u8 data)
451 {
452         int status;
453
454         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
455         struct usb_device *udev = priv->udev;
456
457         status = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
458                                RTL8187_REQ_SET_REGS, RTL8187_REQT_WRITE,
459 #ifdef RTL8192SU
460                                indx, 0, &data, 1, HZ / 2);
461 #else
462                                (indx&0xff)|0xff00, (indx>>8)&0x0f, &data, 1, HZ / 2);
463 #endif
464
465         if (status < 0)
466         {
467                 printk("write_nic_byte TimeOut! status:%d\n", status);
468         }
469
470
471 }
472
473
474 void write_nic_word(struct net_device *dev, int indx, u16 data)
475 {
476
477         int status;
478
479         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
480         struct usb_device *udev = priv->udev;
481
482         status = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
483                                RTL8187_REQ_SET_REGS, RTL8187_REQT_WRITE,
484 #ifdef RTL8192SU
485                                indx, 0, &data, 2, HZ / 2);
486 #else
487                                (indx&0xff)|0xff00, (indx>>8)&0x0f, &data, 2, HZ / 2);
488 #endif
489
490         if (status < 0)
491         {
492                 printk("write_nic_word TimeOut! status:%d\n", status);
493         }
494
495 }
496
497
498 void write_nic_dword(struct net_device *dev, int indx, u32 data)
499 {
500
501         int status;
502
503         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
504         struct usb_device *udev = priv->udev;
505
506         status = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
507                                RTL8187_REQ_SET_REGS, RTL8187_REQT_WRITE,
508 #ifdef RTL8192SU
509                                indx, 0, &data, 4, HZ / 2);
510 #else
511                                (indx&0xff)|0xff00, (indx>>8)&0x0f, &data, 4, HZ / 2);
512 #endif
513
514
515         if (status < 0)
516         {
517                 printk("write_nic_dword TimeOut! status:%d\n", status);
518         }
519
520 }
521
522
523
524 u8 read_nic_byte(struct net_device *dev, int indx)
525 {
526         u8 data;
527         int status;
528         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
529         struct usb_device *udev = priv->udev;
530
531         status = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0),
532                                RTL8187_REQ_GET_REGS, RTL8187_REQT_READ,
533 #ifdef RTL8192SU
534                                indx, 0, &data, 1, HZ / 2);
535 #else
536                                (indx&0xff)|0xff00, (indx>>8)&0x0f, &data, 1, HZ / 2);
537 #endif
538
539         if (status < 0)
540         {
541                 printk("read_nic_byte TimeOut! status:%d\n", status);
542         }
543
544         return data;
545 }
546
547
548
549 u16 read_nic_word(struct net_device *dev, int indx)
550 {
551         u16 data;
552         int status;
553         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
554         struct usb_device *udev = priv->udev;
555
556         status = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0),
557                                RTL8187_REQ_GET_REGS, RTL8187_REQT_READ,
558 #ifdef RTL8192SU
559                                indx, 0, &data, 2, HZ / 2);
560 #else
561                                (indx&0xff)|0xff00, (indx>>8)&0x0f, &data, 2, HZ / 2);
562 #endif
563
564         if (status < 0)
565         {
566                 printk("read_nic_word TimeOut! status:%d\n", status);
567         }
568
569
570         return data;
571 }
572
573 u16 read_nic_word_E(struct net_device *dev, int indx)
574 {
575         u16 data;
576         int status;
577         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
578         struct usb_device *udev = priv->udev;
579
580         status = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0),
581                                RTL8187_REQ_GET_REGS, RTL8187_REQT_READ,
582                                indx|0xfe00, 0, &data, 2, HZ / 2);
583
584         if (status < 0)
585         {
586                 printk("read_nic_word TimeOut! status:%d\n", status);
587         }
588
589
590         return data;
591 }
592
593 u32 read_nic_dword(struct net_device *dev, int indx)
594 {
595         u32 data;
596         int status;
597 //      int result;
598
599         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
600         struct usb_device *udev = priv->udev;
601
602         status = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0),
603                                RTL8187_REQ_GET_REGS, RTL8187_REQT_READ,
604 #ifdef RTL8192SU
605                                indx, 0, &data, 4, HZ / 2);
606 #else
607                                (indx&0xff)|0xff00, (indx>>8)&0x0f, &data, 4, HZ / 2);
608 #endif
609 //      if(0 != result) {
610 //        printk(KERN_WARNING "read size of data = %d\, date = %d\n", result, data);
611 //      }
612
613         if (status < 0)
614         {
615                 printk("read_nic_dword TimeOut! status:%d\n", status);
616                 if(status == -ENODEV) {
617                         priv->usb_error = true;
618                 }
619         }
620
621
622
623         return data;
624 }
625
626
627 //u8 read_phy_cck(struct net_device *dev, u8 adr);
628 //u8 read_phy_ofdm(struct net_device *dev, u8 adr);
629 /* this might still called in what was the PHY rtl8185/rtl8192 common code
630  * plans are to possibilty turn it again in one common code...
631  */
632 inline void force_pci_posting(struct net_device *dev)
633 {
634 }
635
636
637 static struct net_device_stats *rtl8192_stats(struct net_device *dev);
638 void rtl8192_commit(struct net_device *dev);
639 //void rtl8192_restart(struct net_device *dev);
640 void rtl8192_restart(struct work_struct *work);
641 //void rtl8192_rq_tx_ack(struct work_struct *work);
642
643 void watch_dog_timer_callback(unsigned long data);
644
645 /****************************************************************************
646    -----------------------------PROCFS STUFF-------------------------
647 *****************************************************************************/
648
649 static struct proc_dir_entry *rtl8192_proc = NULL;
650
651
652
653 static int proc_get_stats_ap(char *page, char **start,
654                           off_t offset, int count,
655                           int *eof, void *data)
656 {
657         struct net_device *dev = data;
658         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
659         struct ieee80211_device *ieee = priv->ieee80211;
660         struct ieee80211_network *target;
661
662         int len = 0;
663
664         list_for_each_entry(target, &ieee->network_list, list) {
665
666                 len += snprintf(page + len, count - len,
667                 "%s ", target->ssid);
668
669                 if(target->wpa_ie_len>0 || target->rsn_ie_len>0){
670                         len += snprintf(page + len, count - len,
671                         "WPA\n");
672                 }
673                 else{
674                         len += snprintf(page + len, count - len,
675                         "non_WPA\n");
676                 }
677
678         }
679
680         *eof = 1;
681         return len;
682 }
683
684 #ifdef RTL8192SU
685 static int proc_get_registers(char *page, char **start,
686                           off_t offset, int count,
687                           int *eof, void *data)
688 {
689         struct net_device *dev = data;
690 //      struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
691
692         int len = 0;
693         int i,n,page0,page1,page2;
694
695         int max=0xff;
696         page0 = 0x000;
697         page1 = 0x100;
698         page2 = 0x800;
699
700         /* This dump the current register page */
701         if(!IS_BB_REG_OFFSET_92S(page0)){
702                 len += snprintf(page + len, count - len,
703                                 "\n####################page %x##################\n ", (page0>>8));
704                 for(n=0;n<=max;)
705                 {
706                         len += snprintf(page + len, count - len,
707                                         "\nD:  %2x > ",n);
708                         for(i=0;i<16 && n<=max;i++,n++)
709                                 len += snprintf(page + len, count - len,
710                                                 "%2.2x ",read_nic_byte(dev,(page0|n)));
711                 }
712         }else{
713                 len += snprintf(page + len, count - len,
714                                 "\n####################page %x##################\n ", (page0>>8));
715                 for(n=0;n<=max;)
716                 {
717                         len += snprintf(page + len, count - len, "\nD:  %2x > ",n);
718                         for(i=0;i<4 && n<=max;n+=4,i++)
719                                 len += snprintf(page + len, count - len,
720                                                 "%8.8x ",rtl8192_QueryBBReg(dev,(page0|n), bMaskDWord));
721                 }
722         }
723         len += snprintf(page + len, count - len,"\n");
724         *eof = 1;
725         return len;
726
727 }
728 static int proc_get_registers_1(char *page, char **start,
729                           off_t offset, int count,
730                           int *eof, void *data)
731 {
732         struct net_device *dev = data;
733 //      struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
734
735         int len = 0;
736         int i,n,page0;
737
738         int max=0xff;
739         page0 = 0x100;
740
741         /* This dump the current register page */
742                 len += snprintf(page + len, count - len,
743                                 "\n####################page %x##################\n ", (page0>>8));
744                 for(n=0;n<=max;)
745                 {
746                         len += snprintf(page + len, count - len,
747                                         "\nD:  %2x > ",n);
748                         for(i=0;i<16 && n<=max;i++,n++)
749                                 len += snprintf(page + len, count - len,
750                                                 "%2.2x ",read_nic_byte(dev,(page0|n)));
751                 }
752         len += snprintf(page + len, count - len,"\n");
753         *eof = 1;
754         return len;
755
756 }
757 static int proc_get_registers_2(char *page, char **start,
758                           off_t offset, int count,
759                           int *eof, void *data)
760 {
761         struct net_device *dev = data;
762 //      struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
763
764         int len = 0;
765         int i,n,page0;
766
767         int max=0xff;
768         page0 = 0x200;
769
770         /* This dump the current register page */
771                 len += snprintf(page + len, count - len,
772                                 "\n####################page %x##################\n ", (page0>>8));
773                 for(n=0;n<=max;)
774                 {
775                         len += snprintf(page + len, count - len,
776                                         "\nD:  %2x > ",n);
777                         for(i=0;i<16 && n<=max;i++,n++)
778                                 len += snprintf(page + len, count - len,
779                                                 "%2.2x ",read_nic_byte(dev,(page0|n)));
780                 }
781         len += snprintf(page + len, count - len,"\n");
782         *eof = 1;
783         return len;
784
785 }
786 static int proc_get_registers_8(char *page, char **start,
787                           off_t offset, int count,
788                           int *eof, void *data)
789 {
790         struct net_device *dev = data;
791
792         int len = 0;
793         int i,n,page0;
794
795         int max=0xff;
796         page0 = 0x800;
797
798         /* This dump the current register page */
799                 len += snprintf(page + len, count - len,
800                                 "\n####################page %x##################\n ", (page0>>8));
801                 for(n=0;n<=max;)
802                 {
803                         len += snprintf(page + len, count - len, "\nD:  %2x > ",n);
804                         for(i=0;i<4 && n<=max;n+=4,i++)
805                                 len += snprintf(page + len, count - len,
806                                                 "%8.8x ",rtl8192_QueryBBReg(dev,(page0|n), bMaskDWord));
807                 }
808         len += snprintf(page + len, count - len,"\n");
809         *eof = 1;
810         return len;
811
812         }
813 static int proc_get_registers_9(char *page, char **start,
814                           off_t offset, int count,
815                           int *eof, void *data)
816 {
817         struct net_device *dev = data;
818 //      struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
819
820         int len = 0;
821         int i,n,page0;
822
823         int max=0xff;
824         page0 = 0x900;
825
826         /* This dump the current register page */
827                 len += snprintf(page + len, count - len,
828                                 "\n####################page %x##################\n ", (page0>>8));
829                 for(n=0;n<=max;)
830                 {
831                         len += snprintf(page + len, count - len, "\nD:  %2x > ",n);
832                         for(i=0;i<4 && n<=max;n+=4,i++)
833                         len += snprintf(page + len, count - len,
834                                                 "%8.8x ",rtl8192_QueryBBReg(dev,(page0|n), bMaskDWord));
835                 }
836         len += snprintf(page + len, count - len,"\n");
837         *eof = 1;
838         return len;
839 }
840 static int proc_get_registers_a(char *page, char **start,
841                           off_t offset, int count,
842                           int *eof, void *data)
843 {
844         struct net_device *dev = data;
845 //      struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
846
847         int len = 0;
848         int i,n,page0;
849
850         int max=0xff;
851         page0 = 0xa00;
852
853         /* This dump the current register page */
854                                 len += snprintf(page + len, count - len,
855                                 "\n####################page %x##################\n ", (page0>>8));
856                 for(n=0;n<=max;)
857                 {
858                         len += snprintf(page + len, count - len, "\nD:  %2x > ",n);
859                         for(i=0;i<4 && n<=max;n+=4,i++)
860                                 len += snprintf(page + len, count - len,
861                                                 "%8.8x ",rtl8192_QueryBBReg(dev,(page0|n), bMaskDWord));
862                 }
863         len += snprintf(page + len, count - len,"\n");
864         *eof = 1;
865         return len;
866 }
867 static int proc_get_registers_b(char *page, char **start,
868                           off_t offset, int count,
869                           int *eof, void *data)
870 {
871         struct net_device *dev = data;
872 //      struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
873
874         int len = 0;
875         int i,n,page0;
876
877         int max=0xff;
878         page0 = 0xb00;
879
880         /* This dump the current register page */
881                 len += snprintf(page + len, count - len,
882                                 "\n####################page %x##################\n ", (page0>>8));
883                 for(n=0;n<=max;)
884                 {
885                         len += snprintf(page + len, count - len, "\nD:  %2x > ",n);
886                         for(i=0;i<4 && n<=max;n+=4,i++)
887                                 len += snprintf(page + len, count - len,
888                                                 "%8.8x ",rtl8192_QueryBBReg(dev,(page0|n), bMaskDWord));
889                 }
890         len += snprintf(page + len, count - len,"\n");
891         *eof = 1;
892         return len;
893         }
894 static int proc_get_registers_c(char *page, char **start,
895                           off_t offset, int count,
896                           int *eof, void *data)
897 {
898         struct net_device *dev = data;
899 //      struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
900
901         int len = 0;
902         int i,n,page0;
903
904         int max=0xff;
905         page0 = 0xc00;
906
907         /* This dump the current register page */
908                 len += snprintf(page + len, count - len,
909                                 "\n####################page %x##################\n ", (page0>>8));
910                 for(n=0;n<=max;)
911                 {
912                         len += snprintf(page + len, count - len, "\nD:  %2x > ",n);
913                         for(i=0;i<4 && n<=max;n+=4,i++)
914                                 len += snprintf(page + len, count - len,
915                                                 "%8.8x ",rtl8192_QueryBBReg(dev,(page0|n), bMaskDWord));
916                 }
917         len += snprintf(page + len, count - len,"\n");
918         *eof = 1;
919         return len;
920 }
921 static int proc_get_registers_d(char *page, char **start,
922                           off_t offset, int count,
923                           int *eof, void *data)
924 {
925         struct net_device *dev = data;
926 //      struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
927
928         int len = 0;
929         int i,n,page0;
930
931         int max=0xff;
932         page0 = 0xd00;
933
934         /* This dump the current register page */
935                 len += snprintf(page + len, count - len,
936                                 "\n####################page %x##################\n ", (page0>>8));
937                 for(n=0;n<=max;)
938                 {
939                         len += snprintf(page + len, count - len, "\nD:  %2x > ",n);
940                         for(i=0;i<4 && n<=max;n+=4,i++)
941                                 len += snprintf(page + len, count - len,
942                                                 "%8.8x ",rtl8192_QueryBBReg(dev,(page0|n), bMaskDWord));
943                 }
944         len += snprintf(page + len, count - len,"\n");
945         *eof = 1;
946         return len;
947 }
948 static int proc_get_registers_e(char *page, char **start,
949                           off_t offset, int count,
950                           int *eof, void *data)
951 {
952         struct net_device *dev = data;
953 //      struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
954
955         int len = 0;
956         int i,n,page0;
957
958         int max=0xff;
959         page0 = 0xe00;
960
961         /* This dump the current register page */
962                 len += snprintf(page + len, count - len,
963                                 "\n####################page %x##################\n ", (page0>>8));
964                 for(n=0;n<=max;)
965                 {
966                         len += snprintf(page + len, count - len, "\nD:  %2x > ",n);
967                         for(i=0;i<4 && n<=max;n+=4,i++)
968                                 len += snprintf(page + len, count - len,
969                                                 "%8.8x ",rtl8192_QueryBBReg(dev,(page0|n), bMaskDWord));
970                 }
971         len += snprintf(page + len, count - len,"\n");
972         *eof = 1;
973         return len;
974 }
975 #else
976 static int proc_get_registers(char *page, char **start,
977                           off_t offset, int count,
978                           int *eof, void *data)
979 {
980         struct net_device *dev = data;
981 //      struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
982
983         int len = 0;
984         int i,n;
985
986         int max=0xff;
987
988         /* This dump the current register page */
989 len += snprintf(page + len, count - len,
990                         "\n####################page 0##################\n ");
991
992         for(n=0;n<=max;)
993         {
994                 //printk( "\nD: %2x> ", n);
995                 len += snprintf(page + len, count - len,
996                         "\nD:  %2x > ",n);
997
998                 for(i=0;i<16 && n<=max;i++,n++)
999                 len += snprintf(page + len, count - len,
1000                         "%2x ",read_nic_byte(dev,0x000|n));
1001
1002                 //      printk("%2x ",read_nic_byte(dev,n));
1003         }
1004 #if 1
1005 len += snprintf(page + len, count - len,
1006                         "\n####################page 1##################\n ");
1007         for(n=0;n<=max;)
1008         {
1009                 //printk( "\nD: %2x> ", n);
1010                 len += snprintf(page + len, count - len,
1011                         "\nD:  %2x > ",n);
1012
1013                 for(i=0;i<16 && n<=max;i++,n++)
1014                 len += snprintf(page + len, count - len,
1015                         "%2x ",read_nic_byte(dev,0x100|n));
1016
1017                 //      printk("%2x ",read_nic_byte(dev,n));
1018         }
1019 len += snprintf(page + len, count - len,
1020                         "\n####################page 3##################\n ");
1021         for(n=0;n<=max;)
1022         {
1023                 //printk( "\nD: %2x> ", n);
1024                 len += snprintf(page + len, count - len,
1025                         "\nD:  %2x > ",n);
1026
1027                 for(i=0;i<16 && n<=max;i++,n++)
1028                 len += snprintf(page + len, count - len,
1029                         "%2x ",read_nic_byte(dev,0x300|n));
1030
1031                 //      printk("%2x ",read_nic_byte(dev,n));
1032         }
1033
1034 #endif
1035
1036         len += snprintf(page + len, count - len,"\n");
1037         *eof = 1;
1038         return len;
1039
1040 }
1041 #endif
1042
1043 #if 0
1044 static int proc_get_cck_reg(char *page, char **start,
1045                           off_t offset, int count,
1046                           int *eof, void *data)
1047 {
1048         struct net_device *dev = data;
1049 //      struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
1050
1051         int len = 0;
1052         int i,n;
1053
1054         int max = 0x5F;
1055
1056         /* This dump the current register page */
1057         for(n=0;n<=max;)
1058         {
1059                 //printk( "\nD: %2x> ", n);
1060                 len += snprintf(page + len, count - len,
1061                         "\nD:  %2x > ",n);
1062
1063                 for(i=0;i<16 && n<=max;i++,n++)
1064                 len += snprintf(page + len, count - len,
1065                         "%2x ",read_phy_cck(dev,n));
1066
1067                 //      printk("%2x ",read_nic_byte(dev,n));
1068         }
1069         len += snprintf(page + len, count - len,"\n");
1070
1071
1072         *eof = 1;
1073         return len;
1074 }
1075
1076 #endif
1077
1078 #if 0
1079 static int proc_get_ofdm_reg(char *page, char **start,
1080                           off_t offset, int count,
1081                           int *eof, void *data)
1082 {
1083         struct net_device *dev = data;
1084 //      struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
1085
1086         int len = 0;
1087         int i,n;
1088
1089         //int max=0xff;
1090         int max = 0x40;
1091
1092         /* This dump the current register page */
1093         for(n=0;n<=max;)
1094         {
1095                 //printk( "\nD: %2x> ", n);
1096                 len += snprintf(page + len, count - len,
1097                         "\nD:  %2x > ",n);
1098
1099                 for(i=0;i<16 && n<=max;i++,n++)
1100                 len += snprintf(page + len, count - len,
1101                         "%2x ",read_phy_ofdm(dev,n));
1102
1103                 //      printk("%2x ",read_nic_byte(dev,n));
1104         }
1105         len += snprintf(page + len, count - len,"\n");
1106
1107
1108
1109         *eof = 1;
1110         return len;
1111 }
1112
1113 #endif
1114
1115 #if 0
1116 static int proc_get_stats_hw(char *page, char **start,
1117                           off_t offset, int count,
1118                           int *eof, void *data)
1119 {
1120         struct net_device *dev = data;
1121         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
1122
1123         int len = 0;
1124
1125         len += snprintf(page + len, count - len,
1126                 "NIC int: %lu\n"
1127                 "Total int: %lu\n",
1128                 priv->stats.ints,
1129                 priv->stats.shints);
1130
1131         *eof = 1;
1132         return len;
1133 }
1134 #endif
1135
1136 static int proc_get_stats_tx(char *page, char **start,
1137                           off_t offset, int count,
1138                           int *eof, void *data)
1139 {
1140         struct net_device *dev = data;
1141         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
1142
1143         int len = 0;
1144
1145         len += snprintf(page + len, count - len,
1146                 "TX VI priority ok int: %lu\n"
1147                 "TX VI priority error int: %lu\n"
1148                 "TX VO priority ok int: %lu\n"
1149                 "TX VO priority error int: %lu\n"
1150                 "TX BE priority ok int: %lu\n"
1151                 "TX BE priority error int: %lu\n"
1152                 "TX BK priority ok int: %lu\n"
1153                 "TX BK priority error int: %lu\n"
1154                 "TX MANAGE priority ok int: %lu\n"
1155                 "TX MANAGE priority error int: %lu\n"
1156                 "TX BEACON priority ok int: %lu\n"
1157                 "TX BEACON priority error int: %lu\n"
1158 //              "TX high priority ok int: %lu\n"
1159 //              "TX high priority failed error int: %lu\n"
1160                 "TX queue resume: %lu\n"
1161                 "TX queue stopped?: %d\n"
1162                 "TX fifo overflow: %lu\n"
1163 //              "TX beacon: %lu\n"
1164                 "TX VI queue: %d\n"
1165                 "TX VO queue: %d\n"
1166                 "TX BE queue: %d\n"
1167                 "TX BK queue: %d\n"
1168 //              "TX HW queue: %d\n"
1169                 "TX VI dropped: %lu\n"
1170                 "TX VO dropped: %lu\n"
1171                 "TX BE dropped: %lu\n"
1172                 "TX BK dropped: %lu\n"
1173                 "TX total data packets %lu\n",
1174 //              "TX beacon aborted: %lu\n",
1175                 priv->stats.txviokint,
1176                 priv->stats.txvierr,
1177                 priv->stats.txvookint,
1178                 priv->stats.txvoerr,
1179                 priv->stats.txbeokint,
1180                 priv->stats.txbeerr,
1181                 priv->stats.txbkokint,
1182                 priv->stats.txbkerr,
1183                 priv->stats.txmanageokint,
1184                 priv->stats.txmanageerr,
1185                 priv->stats.txbeaconokint,
1186                 priv->stats.txbeaconerr,
1187 //              priv->stats.txhpokint,
1188 //              priv->stats.txhperr,
1189                 priv->stats.txresumed,
1190                 netif_queue_stopped(dev),
1191                 priv->stats.txoverflow,
1192 //              priv->stats.txbeacon,
1193                 atomic_read(&(priv->tx_pending[VI_PRIORITY])),
1194                 atomic_read(&(priv->tx_pending[VO_PRIORITY])),
1195                 atomic_read(&(priv->tx_pending[BE_PRIORITY])),
1196                 atomic_read(&(priv->tx_pending[BK_PRIORITY])),
1197 //              read_nic_byte(dev, TXFIFOCOUNT),
1198                 priv->stats.txvidrop,
1199                 priv->stats.txvodrop,
1200                 priv->stats.txbedrop,
1201                 priv->stats.txbkdrop,
1202                 priv->stats.txdatapkt
1203 //              priv->stats.txbeaconerr
1204                 );
1205
1206         *eof = 1;
1207         return len;
1208 }
1209
1210
1211
1212 static int proc_get_stats_rx(char *page, char **start,
1213                           off_t offset, int count,
1214                           int *eof, void *data)
1215 {
1216         struct net_device *dev = data;
1217         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
1218
1219         int len = 0;
1220
1221         len += snprintf(page + len, count - len,
1222                 "RX packets: %lu\n"
1223                 "RX urb status error: %lu\n"
1224                 "RX invalid urb error: %lu\n",
1225                 priv->stats.rxoktotal,
1226                 priv->stats.rxstaterr,
1227                 priv->stats.rxurberr);
1228
1229         *eof = 1;
1230         return len;
1231 }
1232
1233 void rtl8192_proc_module_init(void)
1234 {
1235         RT_TRACE(COMP_INIT, "Initializing proc filesystem");
1236         rtl8192_proc=create_proc_entry(RTL819xU_MODULE_NAME, S_IFDIR, init_net.proc_net);
1237 }
1238
1239
1240 void rtl8192_proc_module_remove(void)
1241 {
1242         remove_proc_entry(RTL819xU_MODULE_NAME, init_net.proc_net);
1243 }
1244
1245
1246 void rtl8192_proc_remove_one(struct net_device *dev)
1247 {
1248         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
1249
1250
1251         if (priv->dir_dev) {
1252         //      remove_proc_entry("stats-hw", priv->dir_dev);
1253                 remove_proc_entry("stats-tx", priv->dir_dev);
1254                 remove_proc_entry("stats-rx", priv->dir_dev);
1255         //      remove_proc_entry("stats-ieee", priv->dir_dev);
1256                 remove_proc_entry("stats-ap", priv->dir_dev);
1257                 remove_proc_entry("registers", priv->dir_dev);
1258                 remove_proc_entry("registers-1", priv->dir_dev);
1259                 remove_proc_entry("registers-2", priv->dir_dev);
1260                 remove_proc_entry("registers-8", priv->dir_dev);
1261                 remove_proc_entry("registers-9", priv->dir_dev);
1262                 remove_proc_entry("registers-a", priv->dir_dev);
1263                 remove_proc_entry("registers-b", priv->dir_dev);
1264                 remove_proc_entry("registers-c", priv->dir_dev);
1265                 remove_proc_entry("registers-d", priv->dir_dev);
1266                 remove_proc_entry("registers-e", priv->dir_dev);
1267         //      remove_proc_entry("cck-registers",priv->dir_dev);
1268         //      remove_proc_entry("ofdm-registers",priv->dir_dev);
1269                 //remove_proc_entry(dev->name, rtl8192_proc);
1270                 remove_proc_entry("wlan0", rtl8192_proc);
1271                 priv->dir_dev = NULL;
1272         }
1273 }
1274
1275
1276 void rtl8192_proc_init_one(struct net_device *dev)
1277 {
1278         struct proc_dir_entry *e;
1279         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
1280         priv->dir_dev = create_proc_entry(dev->name,
1281                                           S_IFDIR | S_IRUGO | S_IXUGO,
1282                                           rtl8192_proc);
1283         if (!priv->dir_dev) {
1284                 RT_TRACE(COMP_ERR, "Unable to initialize /proc/net/rtl8192/%s\n",
1285                       dev->name);
1286                 return;
1287         }
1288         #if 0
1289         e = create_proc_read_entry("stats-hw", S_IFREG | S_IRUGO,
1290                                    priv->dir_dev, proc_get_stats_hw, dev);
1291
1292         if (!e) {
1293                 DMESGE("Unable to initialize "
1294                       "/proc/net/rtl8192/%s/stats-hw\n",
1295                       dev->name);
1296         }
1297         #endif
1298         e = create_proc_read_entry("stats-rx", S_IFREG | S_IRUGO,
1299                                    priv->dir_dev, proc_get_stats_rx, dev);
1300
1301         if (!e) {
1302                 RT_TRACE(COMP_ERR,"Unable to initialize "
1303                       "/proc/net/rtl8192/%s/stats-rx\n",
1304                       dev->name);
1305         }
1306
1307
1308         e = create_proc_read_entry("stats-tx", S_IFREG | S_IRUGO,
1309                                    priv->dir_dev, proc_get_stats_tx, dev);
1310
1311         if (!e) {
1312                 RT_TRACE(COMP_ERR, "Unable to initialize "
1313                       "/proc/net/rtl8192/%s/stats-tx\n",
1314                       dev->name);
1315         }
1316         #if 0
1317         e = create_proc_read_entry("stats-ieee", S_IFREG | S_IRUGO,
1318                                    priv->dir_dev, proc_get_stats_ieee, dev);
1319
1320         if (!e) {
1321                 DMESGE("Unable to initialize "
1322                       "/proc/net/rtl8192/%s/stats-ieee\n",
1323                       dev->name);
1324         }
1325
1326         #endif
1327
1328         e = create_proc_read_entry("stats-ap", S_IFREG | S_IRUGO,
1329                                    priv->dir_dev, proc_get_stats_ap, dev);
1330
1331         if (!e) {
1332                 RT_TRACE(COMP_ERR, "Unable to initialize "
1333                       "/proc/net/rtl8192/%s/stats-ap\n",
1334                       dev->name);
1335         }
1336
1337         e = create_proc_read_entry("registers", S_IFREG | S_IRUGO,
1338                                    priv->dir_dev, proc_get_registers, dev);
1339         if (!e) {
1340                 RT_TRACE(COMP_ERR, "Unable to initialize "
1341                       "/proc/net/rtl8192/%s/registers\n",
1342                       dev->name);
1343         }
1344 #ifdef RTL8192SU
1345         e = create_proc_read_entry("registers-1", S_IFREG | S_IRUGO,
1346                                    priv->dir_dev, proc_get_registers_1, dev);
1347         if (!e) {
1348                 RT_TRACE(COMP_ERR, "Unable to initialize "
1349                       "/proc/net/rtl8192/%s/registers-1\n",
1350                       dev->name);
1351         }
1352         e = create_proc_read_entry("registers-2", S_IFREG | S_IRUGO,
1353                                    priv->dir_dev, proc_get_registers_2, dev);
1354         if (!e) {
1355                 RT_TRACE(COMP_ERR, "Unable to initialize "
1356                       "/proc/net/rtl8192/%s/registers-2\n",
1357                       dev->name);
1358         }
1359         e = create_proc_read_entry("registers-8", S_IFREG | S_IRUGO,
1360                                    priv->dir_dev, proc_get_registers_8, dev);
1361         if (!e) {
1362                 RT_TRACE(COMP_ERR, "Unable to initialize "
1363                       "/proc/net/rtl8192/%s/registers-8\n",
1364                       dev->name);
1365         }
1366         e = create_proc_read_entry("registers-9", S_IFREG | S_IRUGO,
1367                                    priv->dir_dev, proc_get_registers_9, dev);
1368         if (!e) {
1369                 RT_TRACE(COMP_ERR, "Unable to initialize "
1370                       "/proc/net/rtl8192/%s/registers-9\n",
1371                       dev->name);
1372         }
1373         e = create_proc_read_entry("registers-a", S_IFREG | S_IRUGO,
1374                                    priv->dir_dev, proc_get_registers_a, dev);
1375         if (!e) {
1376                 RT_TRACE(COMP_ERR, "Unable to initialize "
1377                       "/proc/net/rtl8192/%s/registers-a\n",
1378                       dev->name);
1379         }
1380         e = create_proc_read_entry("registers-b", S_IFREG | S_IRUGO,
1381                                    priv->dir_dev, proc_get_registers_b, dev);
1382         if (!e) {
1383                 RT_TRACE(COMP_ERR, "Unable to initialize "
1384                       "/proc/net/rtl8192/%s/registers-b\n",
1385                       dev->name);
1386         }
1387         e = create_proc_read_entry("registers-c", S_IFREG | S_IRUGO,
1388                                    priv->dir_dev, proc_get_registers_c, dev);
1389         if (!e) {
1390                 RT_TRACE(COMP_ERR, "Unable to initialize "
1391                       "/proc/net/rtl8192/%s/registers-c\n",
1392                       dev->name);
1393         }
1394         e = create_proc_read_entry("registers-d", S_IFREG | S_IRUGO,
1395                                    priv->dir_dev, proc_get_registers_d, dev);
1396         if (!e) {
1397                 RT_TRACE(COMP_ERR, "Unable to initialize "
1398                       "/proc/net/rtl8192/%s/registers-d\n",
1399                       dev->name);
1400         }
1401         e = create_proc_read_entry("registers-e", S_IFREG | S_IRUGO,
1402                                    priv->dir_dev, proc_get_registers_e, dev);
1403         if (!e) {
1404                 RT_TRACE(COMP_ERR, "Unable to initialize "
1405                       "/proc/net/rtl8192/%s/registers-e\n",
1406                       dev->name);
1407         }
1408 #endif
1409 #if 0
1410         e = create_proc_read_entry("cck-registers", S_IFREG | S_IRUGO,
1411                                    priv->dir_dev, proc_get_cck_reg, dev);
1412         if (!e) {
1413                 RT_TRACE(COMP_ERR, "Unable to initialize "
1414                       "/proc/net/rtl8192/%s/cck-registers\n",
1415                       dev->name);
1416         }
1417
1418         e = create_proc_read_entry("ofdm-registers", S_IFREG | S_IRUGO,
1419                                    priv->dir_dev, proc_get_ofdm_reg, dev);
1420         if (!e) {
1421                 RT_TRACE(COMP_ERR, "Unable to initialize "
1422                       "/proc/net/rtl8192/%s/ofdm-registers\n",
1423                       dev->name);
1424         }
1425 #endif
1426 }
1427 /****************************************************************************
1428    -----------------------------MISC STUFF-------------------------
1429 *****************************************************************************/
1430
1431 /* this is only for debugging */
1432 void print_buffer(u32 *buffer, int len)
1433 {
1434         int i;
1435         u8 *buf =(u8*)buffer;
1436
1437         printk("ASCII BUFFER DUMP (len: %x):\n",len);
1438
1439         for(i=0;i<len;i++)
1440                 printk("%c",buf[i]);
1441
1442         printk("\nBINARY BUFFER DUMP (len: %x):\n",len);
1443
1444         for(i=0;i<len;i++)
1445                 printk("%x",buf[i]);
1446
1447         printk("\n");
1448 }
1449
1450 //short check_nic_enough_desc(struct net_device *dev, priority_t priority)
1451 short check_nic_enough_desc(struct net_device *dev,int queue_index)
1452 {
1453         struct r8192_priv *priv = ieee80211_priv(dev);
1454         int used = atomic_read(&priv->tx_pending[queue_index]);
1455
1456         return (used < MAX_TX_URB);
1457 }
1458
1459 void tx_timeout(struct net_device *dev)
1460 {
1461         struct r8192_priv *priv = ieee80211_priv(dev);
1462         //rtl8192_commit(dev);
1463
1464         schedule_work(&priv->reset_wq);
1465         //DMESG("TXTIMEOUT");
1466 }
1467
1468
1469 /* this is only for debug */
1470 void dump_eprom(struct net_device *dev)
1471 {
1472         int i;
1473         for(i=0; i<63; i++)
1474                 RT_TRACE(COMP_EPROM, "EEPROM addr %x : %x", i, eprom_read(dev,i));
1475 }
1476
1477 /* this is only for debug */
1478 void rtl8192_dump_reg(struct net_device *dev)
1479 {
1480         int i;
1481         int n;
1482         int max=0x1ff;
1483
1484         RT_TRACE(COMP_PHY, "Dumping NIC register map");
1485
1486         for(n=0;n<=max;)
1487         {
1488                 printk( "\nD: %2x> ", n);
1489                 for(i=0;i<16 && n<=max;i++,n++)
1490                         printk("%2x ",read_nic_byte(dev,n));
1491         }
1492         printk("\n");
1493 }
1494
1495 /****************************************************************************
1496       ------------------------------HW STUFF---------------------------
1497 *****************************************************************************/
1498
1499 #if 0
1500 void rtl8192_irq_enable(struct net_device *dev)
1501 {
1502         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
1503         //priv->irq_enabled = 1;
1504 /*
1505         write_nic_word(dev,INTA_MASK,INTA_RXOK | INTA_RXDESCERR | INTA_RXOVERFLOW |\
1506         INTA_TXOVERFLOW | INTA_HIPRIORITYDESCERR | INTA_HIPRIORITYDESCOK |\
1507         INTA_NORMPRIORITYDESCERR | INTA_NORMPRIORITYDESCOK |\
1508         INTA_LOWPRIORITYDESCERR | INTA_LOWPRIORITYDESCOK | INTA_TIMEOUT);
1509 */
1510         write_nic_word(dev,INTA_MASK, priv->irq_mask);
1511 }
1512
1513
1514 void rtl8192_irq_disable(struct net_device *dev)
1515 {
1516 //      struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
1517
1518         write_nic_word(dev,INTA_MASK,0);
1519         force_pci_posting(dev);
1520 //      priv->irq_enabled = 0;
1521 }
1522 #endif
1523
1524 void rtl8192_set_mode(struct net_device *dev,int mode)
1525 {
1526         u8 ecmd;
1527         ecmd=read_nic_byte(dev, EPROM_CMD);
1528         ecmd=ecmd &~ EPROM_CMD_OPERATING_MODE_MASK;
1529         ecmd=ecmd | (mode<<EPROM_CMD_OPERATING_MODE_SHIFT);
1530         ecmd=ecmd &~ (1<<EPROM_CS_SHIFT);
1531         ecmd=ecmd &~ (1<<EPROM_CK_SHIFT);
1532         write_nic_byte(dev, EPROM_CMD, ecmd);
1533 }
1534
1535
1536 void rtl8192_update_msr(struct net_device *dev)
1537 {
1538         struct r8192_priv *priv = ieee80211_priv(dev);
1539         u8 msr;
1540
1541         msr  = read_nic_byte(dev, MSR);
1542         msr &= ~ MSR_LINK_MASK;
1543
1544         /* do not change in link_state != WLAN_LINK_ASSOCIATED.
1545          * msr must be updated if the state is ASSOCIATING.
1546          * this is intentional and make sense for ad-hoc and
1547          * master (see the create BSS/IBSS func)
1548          */
1549         if (priv->ieee80211->state == IEEE80211_LINKED){
1550
1551                 if (priv->ieee80211->iw_mode == IW_MODE_INFRA)
1552                         msr |= (MSR_LINK_MANAGED<<MSR_LINK_SHIFT);
1553                 else if (priv->ieee80211->iw_mode == IW_MODE_ADHOC)
1554                         msr |= (MSR_LINK_ADHOC<<MSR_LINK_SHIFT);
1555                 else if (priv->ieee80211->iw_mode == IW_MODE_MASTER)
1556                         msr |= (MSR_LINK_MASTER<<MSR_LINK_SHIFT);
1557
1558         }else
1559                 msr |= (MSR_LINK_NONE<<MSR_LINK_SHIFT);
1560
1561         write_nic_byte(dev, MSR, msr);
1562 }
1563
1564 void rtl8192_set_chan(struct net_device *dev,short ch)
1565 {
1566         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
1567 //      u32 tx;
1568         RT_TRACE(COMP_CH, "=====>%s()====ch:%d\n", __FUNCTION__, ch);
1569         //printk("=====>%s()====ch:%d\n", __FUNCTION__, ch);
1570         priv->chan=ch;
1571         #if 0
1572         if(priv->ieee80211->iw_mode == IW_MODE_ADHOC ||
1573                 priv->ieee80211->iw_mode == IW_MODE_MASTER){
1574
1575                         priv->ieee80211->link_state = WLAN_LINK_ASSOCIATED;
1576                         priv->ieee80211->master_chan = ch;
1577                         rtl8192_update_beacon_ch(dev);
1578                 }
1579         #endif
1580
1581         /* this hack should avoid frame TX during channel setting*/
1582
1583
1584 //      tx = read_nic_dword(dev,TX_CONF);
1585 //      tx &= ~TX_LOOPBACK_MASK;
1586
1587 #ifndef LOOP_TEST
1588 //      write_nic_dword(dev,TX_CONF, tx |( TX_LOOPBACK_MAC<<TX_LOOPBACK_SHIFT));
1589
1590         //need to implement rf set channel here WB
1591
1592         if (priv->rf_set_chan)
1593         priv->rf_set_chan(dev,priv->chan);
1594         mdelay(10);
1595 //      write_nic_dword(dev,TX_CONF,tx | (TX_LOOPBACK_NONE<<TX_LOOPBACK_SHIFT));
1596 #endif
1597 }
1598
1599 static void rtl8192_rx_isr(struct urb *urb);
1600
1601 u32 get_rxpacket_shiftbytes_819xusb(struct ieee80211_rx_stats *pstats)
1602 {
1603
1604                 return (sizeof(rx_desc_819x_usb) + pstats->RxDrvInfoSize
1605                                 + pstats->RxBufShift);
1606
1607 }
1608 static int rtl8192_rx_initiate(struct net_device*dev)
1609 {
1610         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
1611         struct urb *entry;
1612         struct sk_buff *skb;
1613         struct rtl8192_rx_info *info;
1614
1615         /* nomal packet rx procedure */
1616         while (skb_queue_len(&priv->rx_queue) < MAX_RX_URB) {
1617                 skb = __dev_alloc_skb(RX_URB_SIZE, GFP_KERNEL);
1618                 if (!skb)
1619                         break;
1620                 entry = usb_alloc_urb(0, GFP_KERNEL);
1621                 if (!entry) {
1622                         kfree_skb(skb);
1623                         break;
1624                 }
1625 //              printk("nomal packet IN request!\n");
1626                 usb_fill_bulk_urb(entry, priv->udev,
1627                                   usb_rcvbulkpipe(priv->udev, 3), skb->tail,
1628                                   RX_URB_SIZE, rtl8192_rx_isr, skb);
1629                 info = (struct rtl8192_rx_info *) skb->cb;
1630                 info->urb = entry;
1631                 info->dev = dev;
1632                 info->out_pipe = 3; //denote rx normal packet queue
1633                 skb_queue_tail(&priv->rx_queue, skb);
1634                 usb_submit_urb(entry, GFP_KERNEL);
1635         }
1636
1637         /* command packet rx procedure */
1638         while (skb_queue_len(&priv->rx_queue) < MAX_RX_URB + 3) {
1639 //              printk("command packet IN request!\n");
1640                 skb = __dev_alloc_skb(RX_URB_SIZE ,GFP_KERNEL);
1641                 if (!skb)
1642                         break;
1643                 entry = usb_alloc_urb(0, GFP_KERNEL);
1644                 if (!entry) {
1645                         kfree_skb(skb);
1646                         break;
1647                 }
1648                 usb_fill_bulk_urb(entry, priv->udev,
1649                                   usb_rcvbulkpipe(priv->udev, 9), skb->tail,
1650                                   RX_URB_SIZE, rtl8192_rx_isr, skb);
1651                 info = (struct rtl8192_rx_info *) skb->cb;
1652                 info->urb = entry;
1653                 info->dev = dev;
1654                    info->out_pipe = 9; //denote rx cmd packet queue
1655                 skb_queue_tail(&priv->rx_queue, skb);
1656                 usb_submit_urb(entry, GFP_KERNEL);
1657         }
1658
1659         return 0;
1660 }
1661
1662 void rtl8192_set_rxconf(struct net_device *dev)
1663 {
1664         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
1665         u32 rxconf;
1666
1667         rxconf=read_nic_dword(dev,RCR);
1668         rxconf = rxconf &~ MAC_FILTER_MASK;
1669         rxconf = rxconf | RCR_AMF;
1670         rxconf = rxconf | RCR_ADF;
1671         rxconf = rxconf | RCR_AB;
1672         rxconf = rxconf | RCR_AM;
1673         //rxconf = rxconf | RCR_ACF;
1674
1675         if (dev->flags & IFF_PROMISC) {DMESG ("NIC in promisc mode");}
1676
1677         if(priv->ieee80211->iw_mode == IW_MODE_MONITOR || \
1678            dev->flags & IFF_PROMISC){
1679                 rxconf = rxconf | RCR_AAP;
1680         } /*else if(priv->ieee80211->iw_mode == IW_MODE_MASTER){
1681                 rxconf = rxconf | (1<<ACCEPT_ALLMAC_FRAME_SHIFT);
1682                 rxconf = rxconf | (1<<RX_CHECK_BSSID_SHIFT);
1683         }*/else{
1684                 rxconf = rxconf | RCR_APM;
1685                 rxconf = rxconf | RCR_CBSSID;
1686         }
1687
1688
1689         if(priv->ieee80211->iw_mode == IW_MODE_MONITOR){
1690                 rxconf = rxconf | RCR_AICV;
1691                 rxconf = rxconf | RCR_APWRMGT;
1692         }
1693
1694         if( priv->crcmon == 1 && priv->ieee80211->iw_mode == IW_MODE_MONITOR)
1695                 rxconf = rxconf | RCR_ACRC32;
1696
1697
1698         rxconf = rxconf &~ RX_FIFO_THRESHOLD_MASK;
1699         rxconf = rxconf | (RX_FIFO_THRESHOLD_NONE<<RX_FIFO_THRESHOLD_SHIFT);
1700         rxconf = rxconf &~ MAX_RX_DMA_MASK;
1701         rxconf = rxconf | ((u32)7<<RCR_MXDMA_OFFSET);
1702
1703 //      rxconf = rxconf | (1<<RX_AUTORESETPHY_SHIFT);
1704         rxconf = rxconf | RCR_ONLYERLPKT;
1705
1706 //      rxconf = rxconf &~ RCR_CS_MASK;
1707 //      rxconf = rxconf | (1<<RCR_CS_SHIFT);
1708
1709         write_nic_dword(dev, RCR, rxconf);
1710
1711         #ifdef DEBUG_RX
1712         DMESG("rxconf: %x %x",rxconf ,read_nic_dword(dev,RCR));
1713         #endif
1714 }
1715 //wait to be removed
1716 void rtl8192_rx_enable(struct net_device *dev)
1717 {
1718         //u8 cmd;
1719
1720         //struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
1721
1722         rtl8192_rx_initiate(dev);
1723
1724 //      rtl8192_set_rxconf(dev);
1725 #if 0
1726         if(NIC_8187 == priv->card_8187) {
1727                 cmd=read_nic_byte(dev,CMD);
1728                 write_nic_byte(dev,CMD,cmd | (1<<CMD_RX_ENABLE_SHIFT));
1729         }
1730         else {
1731                 //write_nic_dword(dev, RX_CONF, priv->ReceiveConfig);
1732         }
1733 #endif
1734 }
1735
1736
1737 void rtl8192_tx_enable(struct net_device *dev)
1738 {
1739 #if 0
1740         u8 cmd;
1741         u8 byte;
1742         u32 txconf;
1743         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
1744         //test loopback
1745         //      priv->TransmitConfig |= (TX_LOOPBACK_BASEBAND<<TX_LOOPBACK_SHIFT);
1746         if(NIC_8187B == priv->card_8187){
1747                 write_nic_dword(dev, TX_CONF, priv->TransmitConfig);
1748                 byte = read_nic_byte(dev, MSR);
1749                 byte |= MSR_LINK_ENEDCA;
1750                 write_nic_byte(dev, MSR, byte);
1751         } else {
1752                 byte = read_nic_byte(dev,CW_CONF);
1753                 byte &= ~(1<<CW_CONF_PERPACKET_CW_SHIFT);
1754                 byte &= ~(1<<CW_CONF_PERPACKET_RETRY_SHIFT);
1755                 write_nic_byte(dev, CW_CONF, byte);
1756
1757                 byte = read_nic_byte(dev, TX_AGC_CTL);
1758                 byte &= ~(1<<TX_AGC_CTL_PERPACKET_GAIN_SHIFT);
1759                 byte &= ~(1<<TX_AGC_CTL_PERPACKET_ANTSEL_SHIFT);
1760                 byte &= ~(1<<TX_AGC_CTL_FEEDBACK_ANT);
1761                 write_nic_byte(dev, TX_AGC_CTL, byte);
1762
1763                 txconf= read_nic_dword(dev,TX_CONF);
1764
1765
1766                 txconf = txconf &~ TX_LOOPBACK_MASK;
1767
1768 #ifndef LOOP_TEST
1769                 txconf = txconf | (TX_LOOPBACK_NONE<<TX_LOOPBACK_SHIFT);
1770 #else
1771                 txconf = txconf | (TX_LOOPBACK_BASEBAND<<TX_LOOPBACK_SHIFT);
1772 #endif
1773                 txconf = txconf &~ TCR_SRL_MASK;
1774                 txconf = txconf &~ TCR_LRL_MASK;
1775
1776                 txconf = txconf | (priv->retry_data<<TX_LRLRETRY_SHIFT); // long
1777                 txconf = txconf | (priv->retry_rts<<TX_SRLRETRY_SHIFT); // short
1778
1779                 txconf = txconf &~ (1<<TX_NOCRC_SHIFT);
1780
1781                 txconf = txconf &~ TCR_MXDMA_MASK;
1782                 txconf = txconf | (TCR_MXDMA_2048<<TCR_MXDMA_SHIFT);
1783
1784                 txconf = txconf | TCR_DISReqQsize;
1785                 txconf = txconf | TCR_DISCW;
1786                 txconf = txconf &~ TCR_SWPLCPLEN;
1787
1788                 txconf=txconf | (1<<TX_NOICV_SHIFT);
1789
1790                 write_nic_dword(dev,TX_CONF,txconf);
1791
1792 #ifdef DEBUG_TX
1793                 DMESG("txconf: %x %x",txconf,read_nic_dword(dev,TX_CONF));
1794 #endif
1795
1796                 cmd=read_nic_byte(dev,CMD);
1797                 write_nic_byte(dev,CMD,cmd | (1<<CMD_TX_ENABLE_SHIFT));
1798         }
1799 #endif
1800 }
1801
1802 #if 0
1803 void rtl8192_beacon_tx_enable(struct net_device *dev)
1804 {
1805         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
1806         priv->dma_poll_mask &=~(1<<TX_DMA_STOP_BEACON_SHIFT);
1807         rtl8192_set_mode(dev,EPROM_CMD_CONFIG);
1808         write_nic_byte(dev,TX_DMA_POLLING,priv->dma_poll_mask);
1809         rtl8192_set_mode(dev,EPROM_CMD_NORMAL);
1810 }
1811
1812
1813 void rtl8192_
1814 _disable(struct net_device *dev)
1815 {
1816         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
1817         priv->dma_poll_mask |= (1<<TX_DMA_STOP_BEACON_SHIFT);
1818         rtl8192_set_mode(dev,EPROM_CMD_CONFIG);
1819         write_nic_byte(dev,TX_DMA_POLLING,priv->dma_poll_mask);
1820         rtl8192_set_mode(dev,EPROM_CMD_NORMAL);
1821 }
1822
1823 #endif
1824
1825
1826 void rtl8192_rtx_disable(struct net_device *dev)
1827 {
1828         u8 cmd;
1829         struct r8192_priv *priv = ieee80211_priv(dev);
1830         struct sk_buff *skb;
1831         struct rtl8192_rx_info *info;
1832
1833         cmd=read_nic_byte(dev,CMDR);
1834         write_nic_byte(dev, CMDR, cmd &~ \
1835                 (CR_TE|CR_RE));
1836         force_pci_posting(dev);
1837         mdelay(10);
1838
1839         while ((skb = __skb_dequeue(&priv->rx_queue))) {
1840                 info = (struct rtl8192_rx_info *) skb->cb;
1841                 if (!info->urb)
1842                         continue;
1843
1844                 usb_kill_urb(info->urb);
1845                 kfree_skb(skb);
1846         }
1847
1848         if (skb_queue_len(&priv->skb_queue)) {
1849                 printk(KERN_WARNING "skb_queue not empty\n");
1850         }
1851
1852         skb_queue_purge(&priv->skb_queue);
1853         return;
1854 }
1855
1856
1857 int alloc_tx_beacon_desc_ring(struct net_device *dev, int count)
1858 {
1859         #if 0
1860         int i;
1861         u32 *tmp;
1862         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
1863
1864         priv->txbeaconring = (u32*)pci_alloc_consistent(priv->pdev,
1865                                           sizeof(u32)*8*count,
1866                                           &priv->txbeaconringdma);
1867         if (!priv->txbeaconring) return -1;
1868         for (tmp=priv->txbeaconring,i=0;i<count;i++){
1869                 *tmp = *tmp &~ (1<<31); // descriptor empty, owned by the drv
1870                 /*
1871                 *(tmp+2) = (u32)dma_tmp;
1872                 *(tmp+3) = bufsize;
1873                 */
1874                 if(i+1<count)
1875                         *(tmp+4) = (u32)priv->txbeaconringdma+((i+1)*8*4);
1876                 else
1877                         *(tmp+4) = (u32)priv->txbeaconringdma;
1878
1879                 tmp=tmp+8;
1880         }
1881         #endif
1882         return 0;
1883 }
1884
1885 #if 0
1886 void rtl8192_reset(struct net_device *dev)
1887 {
1888
1889         //struct r8192_priv *priv = ieee80211_priv(dev);
1890         //u8 cr;
1891
1892
1893         /* make sure the analog power is on before
1894          * reset, otherwise reset may fail
1895          */
1896 #if 0
1897         if(NIC_8187 == priv->card_8187) {
1898                 rtl8192_set_anaparam(dev, RTL8225_ANAPARAM_ON);
1899                 rtl8185_set_anaparam2(dev, RTL8225_ANAPARAM2_ON);
1900                 rtl8192_irq_disable(dev);
1901                 mdelay(200);
1902                 write_nic_byte_E(dev,0x18,0x10);
1903                 write_nic_byte_E(dev,0x18,0x11);
1904                 write_nic_byte_E(dev,0x18,0x00);
1905                 mdelay(200);
1906         }
1907 #endif
1908         printk("=====>reset?\n");
1909 #if 0
1910         cr=read_nic_byte(dev,CMD);
1911         cr = cr & 2;
1912         cr = cr | (1<<CMD_RST_SHIFT);
1913         write_nic_byte(dev,CMD,cr);
1914
1915         force_pci_posting(dev);
1916
1917         mdelay(200);
1918
1919         if(read_nic_byte(dev,CMD) & (1<<CMD_RST_SHIFT))
1920                 RT_TRACE(COMP_ERR, "Card reset timeout!\n");
1921         else
1922                 RT_TRACE(COMP_DOWN, "Card successfully reset\n");
1923 #endif
1924 #if 0
1925         if(NIC_8187 == priv->card_8187) {
1926
1927                 printk("This is RTL8187 Reset procedure\n");
1928                 rtl8192_set_mode(dev,EPROM_CMD_LOAD);
1929                 force_pci_posting(dev);
1930                 mdelay(200);
1931
1932                 /* after the eeprom load cycle, make sure we have
1933                  * correct anaparams
1934                  */
1935                 rtl8192_set_anaparam(dev, RTL8225_ANAPARAM_ON);
1936                 rtl8185_set_anaparam2(dev, RTL8225_ANAPARAM2_ON);
1937         }
1938         else
1939 #endif
1940                 printk("This is RTL8187B Reset procedure\n");
1941
1942 }
1943 #endif
1944 inline u16 ieeerate2rtlrate(int rate)
1945 {
1946         switch(rate){
1947         case 10:
1948         return 0;
1949         case 20:
1950         return 1;
1951         case 55:
1952         return 2;
1953         case 110:
1954         return 3;
1955         case 60:
1956         return 4;
1957         case 90:
1958         return 5;
1959         case 120:
1960         return 6;
1961         case 180:
1962         return 7;
1963         case 240:
1964         return 8;
1965         case 360:
1966         return 9;
1967         case 480:
1968         return 10;
1969         case 540:
1970         return 11;
1971         default:
1972         return 3;
1973
1974         }
1975 }
1976 static u16 rtl_rate[] = {10,20,55,110,60,90,120,180,240,360,480,540};
1977 inline u16 rtl8192_rate2rate(short rate)
1978 {
1979         if (rate >11) return 0;
1980         return rtl_rate[rate];
1981 }
1982
1983 static void rtl8192_rx_isr(struct urb *urb)
1984 {
1985         struct sk_buff *skb = (struct sk_buff *) urb->context;
1986         struct rtl8192_rx_info *info = (struct rtl8192_rx_info *)skb->cb;
1987         struct net_device *dev = info->dev;
1988         struct r8192_priv *priv = ieee80211_priv(dev);
1989         int out_pipe = info->out_pipe;
1990         int err;
1991         if(!priv->up)
1992                 return;
1993         if (unlikely(urb->status)) {
1994                 info->urb = NULL;
1995                 priv->stats.rxstaterr++;
1996                 priv->ieee80211->stats.rx_errors++;
1997                 usb_free_urb(urb);
1998         //      printk("%s():rx status err\n",__FUNCTION__);
1999                 return;
2000         }
2001
2002         skb_unlink(skb, &priv->rx_queue);
2003         skb_put(skb, urb->actual_length);
2004
2005         skb_queue_tail(&priv->skb_queue, skb);
2006         tasklet_schedule(&priv->irq_rx_tasklet);
2007
2008         skb = dev_alloc_skb(RX_URB_SIZE);
2009         if (unlikely(!skb)) {
2010                 usb_free_urb(urb);
2011                 printk("%s():can,t alloc skb\n",__FUNCTION__);
2012                 /* TODO check rx queue length and refill *somewhere* */
2013                 return;
2014         }
2015
2016         usb_fill_bulk_urb(urb, priv->udev,
2017                         usb_rcvbulkpipe(priv->udev, out_pipe), skb->tail,
2018                         RX_URB_SIZE, rtl8192_rx_isr, skb);
2019
2020         info = (struct rtl8192_rx_info *) skb->cb;
2021         info->urb = urb;
2022         info->dev = dev;
2023         info->out_pipe = out_pipe;
2024
2025         urb->transfer_buffer = skb->tail;
2026         urb->context = skb;
2027         skb_queue_tail(&priv->rx_queue, skb);
2028         err = usb_submit_urb(urb, GFP_ATOMIC);
2029         if(err && err != EPERM)
2030                 printk("can not submit rxurb, err is %x,URB status is %x\n",err,urb->status);
2031 }
2032
2033 u32
2034 rtl819xusb_rx_command_packet(
2035         struct net_device *dev,
2036         struct ieee80211_rx_stats *pstats
2037         )
2038 {
2039         u32     status;
2040
2041         //RT_TRACE(COMP_RECV, DBG_TRACE, ("---> RxCommandPacketHandle819xUsb()\n"));
2042
2043         status = cmpk_message_handle_rx(dev, pstats);
2044         if (status)
2045         {
2046                 DMESG("rxcommandpackethandle819xusb: It is a command packet\n");
2047         }
2048         else
2049         {
2050                 //RT_TRACE(COMP_RECV, DBG_TRACE, ("RxCommandPacketHandle819xUsb: It is not a command packet\n"));
2051         }
2052
2053         //RT_TRACE(COMP_RECV, DBG_TRACE, ("<--- RxCommandPacketHandle819xUsb()\n"));
2054         return status;
2055 }
2056
2057 #if 0
2058 void rtl8192_tx_queues_stop(struct net_device *dev)
2059 {
2060         //struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
2061         u8 dma_poll_mask = (1<<TX_DMA_STOP_LOWPRIORITY_SHIFT);
2062         dma_poll_mask |= (1<<TX_DMA_STOP_HIPRIORITY_SHIFT);
2063         dma_poll_mask |= (1<<TX_DMA_STOP_NORMPRIORITY_SHIFT);
2064         dma_poll_mask |= (1<<TX_DMA_STOP_BEACON_SHIFT);
2065
2066         rtl8192_set_mode(dev,EPROM_CMD_CONFIG);
2067         write_nic_byte(dev,TX_DMA_POLLING,dma_poll_mask);
2068         rtl8192_set_mode(dev,EPROM_CMD_NORMAL);
2069 }
2070 #endif
2071
2072 void rtl8192_data_hard_stop(struct net_device *dev)
2073 {
2074         //FIXME !!
2075         #if 0
2076         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
2077         priv->dma_poll_mask |= (1<<TX_DMA_STOP_LOWPRIORITY_SHIFT);
2078         rtl8192_set_mode(dev,EPROM_CMD_CONFIG);
2079         write_nic_byte(dev,TX_DMA_POLLING,priv->dma_poll_mask);
2080         rtl8192_set_mode(dev,EPROM_CMD_NORMAL);
2081         #endif
2082 }
2083
2084
2085 void rtl8192_data_hard_resume(struct net_device *dev)
2086 {
2087         // FIXME !!
2088         #if 0
2089         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
2090         priv->dma_poll_mask &= ~(1<<TX_DMA_STOP_LOWPRIORITY_SHIFT);
2091         rtl8192_set_mode(dev,EPROM_CMD_CONFIG);
2092         write_nic_byte(dev,TX_DMA_POLLING,priv->dma_poll_mask);
2093         rtl8192_set_mode(dev,EPROM_CMD_NORMAL);
2094         #endif
2095 }
2096
2097 /* this function TX data frames when the ieee80211 stack requires this.
2098  * It checks also if we need to stop the ieee tx queue, eventually do it
2099  */
2100 void rtl8192_hard_data_xmit(struct sk_buff *skb, struct net_device *dev, int rate)
2101 {
2102         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
2103         int ret;
2104         unsigned long flags;
2105         cb_desc *tcb_desc = (cb_desc *)(skb->cb + MAX_DEV_ADDR_SIZE);
2106         u8 queue_index = tcb_desc->queue_index;
2107
2108         /* shall not be referred by command packet */
2109         assert(queue_index != TXCMD_QUEUE);
2110
2111         spin_lock_irqsave(&priv->tx_lock,flags);
2112
2113         memcpy((unsigned char *)(skb->cb),&dev,sizeof(dev));
2114 //      tcb_desc->RATRIndex = 7;
2115 //      tcb_desc->bTxDisableRateFallBack = 1;
2116 //      tcb_desc->bTxUseDriverAssingedRate = 1;
2117         tcb_desc->bTxEnableFwCalcDur = 1;
2118         skb_push(skb, priv->ieee80211->tx_headroom);
2119         ret = priv->ops->rtl819x_tx(dev, skb);
2120
2121         //priv->ieee80211->stats.tx_bytes+=(skb->len - priv->ieee80211->tx_headroom);
2122         //priv->ieee80211->stats.tx_packets++;
2123
2124         spin_unlock_irqrestore(&priv->tx_lock,flags);
2125
2126 //      return ret;
2127         return;
2128 }
2129
2130 /* This is a rough attempt to TX a frame
2131  * This is called by the ieee 80211 stack to TX management frames.
2132  * If the ring is full packet are dropped (for data frame the queue
2133  * is stopped before this can happen).
2134  */
2135 int rtl8192_hard_start_xmit(struct sk_buff *skb,struct net_device *dev)
2136 {
2137         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
2138         int ret;
2139         unsigned long flags;
2140         cb_desc *tcb_desc = (cb_desc *)(skb->cb + MAX_DEV_ADDR_SIZE);
2141         u8 queue_index = tcb_desc->queue_index;
2142
2143
2144         spin_lock_irqsave(&priv->tx_lock,flags);
2145
2146         memcpy((unsigned char *)(skb->cb),&dev,sizeof(dev));
2147         if(queue_index == TXCMD_QUEUE) {
2148                 skb_push(skb, USB_HWDESC_HEADER_LEN);
2149                 priv->ops->rtl819x_tx_cmd(dev, skb);
2150                 ret = 1;
2151                 spin_unlock_irqrestore(&priv->tx_lock,flags);
2152                 return ret;
2153         } else {
2154                 skb_push(skb, priv->ieee80211->tx_headroom);
2155                 ret = priv->ops->rtl819x_tx(dev, skb);
2156         }
2157
2158         spin_unlock_irqrestore(&priv->tx_lock,flags);
2159
2160         return ret;
2161 }
2162
2163
2164 void rtl8192_try_wake_queue(struct net_device *dev, int pri);
2165
2166
2167 static void rtl8192_tx_isr(struct urb *tx_urb)
2168 {
2169         struct sk_buff *skb = (struct sk_buff*)tx_urb->context;
2170         struct net_device *dev = NULL;
2171         struct r8192_priv *priv = NULL;
2172         cb_desc *tcb_desc = (cb_desc *)(skb->cb + MAX_DEV_ADDR_SIZE);
2173         u8  queue_index = tcb_desc->queue_index;
2174 //      bool bToSend0Byte;
2175 //      u16 BufLen = skb->len;
2176
2177         memcpy(&dev,(struct net_device*)(skb->cb),sizeof(struct net_device*));
2178         priv = ieee80211_priv(dev);
2179
2180         if(tcb_desc->queue_index != TXCMD_QUEUE) {
2181                 if(tx_urb->status == 0) {
2182                 //      dev->trans_start = jiffies;
2183                         // As act as station mode, destion shall be  unicast address.
2184                         //priv->ieee80211->stats.tx_bytes+=(skb->len - priv->ieee80211->tx_headroom);
2185                         //priv->ieee80211->stats.tx_packets++;
2186                         priv->stats.txoktotal++;
2187                         priv->ieee80211->LinkDetectInfo.NumTxOkInPeriod++;
2188                         priv->stats.txbytesunicast += (skb->len - priv->ieee80211->tx_headroom);
2189                 } else {
2190                         priv->ieee80211->stats.tx_errors++;
2191                         //priv->stats.txmanageerr++;
2192                         /* TODO */
2193                 }
2194         }
2195
2196         /* free skb and tx_urb */
2197         if(skb != NULL) {
2198                 dev_kfree_skb_any(skb);
2199                 usb_free_urb(tx_urb);
2200                 atomic_dec(&priv->tx_pending[queue_index]);
2201         }
2202
2203 #if 0  //we need to send zero byte packet just after 512 byte(64 byte)packet is transmitted, or we will halt. It will greatly reduced available page in FW, and ruin our throughput. WB 2008.08.27
2204         if(BufLen > 0 && ((BufLen % 512 == 0)||(BufLen % 64 == 0))) {
2205                 bToSend0Byte = true;
2206         }
2207
2208         bToSend0Byte = false;
2209         //
2210         // Note that, we at most handle 1 MPDU to send here, either
2211         // fragment or MPDU in wait queue.
2212         //
2213         if(!bToSend0Byte)
2214 #endif
2215         {
2216                 //
2217                 // Handle HW Beacon:
2218                 // We had transfer our beacon frame to host controler at this moment.
2219                 //
2220 #if 0
2221                 if(tcb_desc->tx_queue == BEACON_QUEUE)
2222                 {
2223                         priv->bSendingBeacon = FALSE;
2224                 }
2225 #endif
2226                 //
2227                 // Caution:
2228                 // Handling the wait queue of command packets.
2229                 // For Tx command packets, we must not do TCB fragment because it is not handled right now.
2230                 // We must cut the packets to match the size of TX_CMD_PKT before we send it.
2231                 //
2232         if (queue_index == MGNT_QUEUE){
2233         if (priv->ieee80211->ack_tx_to_ieee){
2234             if (rtl8192_is_tx_queue_empty(dev)){
2235                 priv->ieee80211->ack_tx_to_ieee = 0;
2236                 ieee80211_ps_tx_ack(priv->ieee80211, 1);
2237             }
2238         }
2239     }
2240                 /* Handle MPDU in wait queue. */
2241                 if(queue_index != BEACON_QUEUE) {
2242                         /* Don't send data frame during scanning.*/
2243                         if((skb_queue_len(&priv->ieee80211->skb_waitQ[queue_index]) != 0)&&\
2244                                         (!(priv->ieee80211->queue_stop))) {
2245                                 if(NULL != (skb = skb_dequeue(&(priv->ieee80211->skb_waitQ[queue_index]))))
2246                                         priv->ieee80211->softmac_hard_start_xmit(skb, dev);
2247
2248                                 return; //modified by david to avoid further processing AMSDU
2249                         }
2250                 }
2251         }
2252
2253 #if 0
2254         else
2255         {
2256                 RT_TRACE( COMP_SEND,"HalUsbOutComplete(%d): bToSend0Byte.\n", PipeIndex);
2257
2258                 //
2259                 // In this case, we don't return skb now.
2260                 // It will be returned when the 0-byte request completed.
2261                 //
2262
2263                 //
2264                 // Bulk out an 0-byte padding transfer.
2265                 //
2266                 HalUsbOut0Byte(pAdapter, PipeIndex, skb);
2267         }
2268
2269 #endif
2270 }
2271
2272 void rtl8192_beacon_stop(struct net_device *dev)
2273 {
2274         u8 msr, msrm, msr2;
2275         struct r8192_priv *priv = ieee80211_priv(dev);
2276
2277         msr  = read_nic_byte(dev, MSR);
2278         msrm = msr & MSR_LINK_MASK;
2279         msr2 = msr & ~MSR_LINK_MASK;
2280
2281         if(NIC_8192U == priv->card_8192) {
2282                 usb_kill_urb(priv->rx_urb[MAX_RX_URB]);
2283         }
2284         if ((msrm == (MSR_LINK_ADHOC<<MSR_LINK_SHIFT) ||
2285                 (msrm == (MSR_LINK_MASTER<<MSR_LINK_SHIFT)))){
2286                 write_nic_byte(dev, MSR, msr2 | MSR_LINK_NONE);
2287                 write_nic_byte(dev, MSR, msr);
2288         }
2289 }
2290
2291 void rtl8192_config_rate(struct net_device* dev, u16* rate_config)
2292 {
2293          struct r8192_priv *priv = ieee80211_priv(dev);
2294          struct ieee80211_network *net;
2295          u8 i=0, basic_rate = 0;
2296          net = & priv->ieee80211->current_network;
2297
2298          for (i=0; i<net->rates_len; i++)
2299          {
2300                  basic_rate = net->rates[i]&0x7f;
2301                  switch(basic_rate)
2302                  {
2303                          case MGN_1M:   *rate_config |= RRSR_1M;        break;
2304                          case MGN_2M:   *rate_config |= RRSR_2M;        break;
2305                          case MGN_5_5M: *rate_config |= RRSR_5_5M;      break;
2306                          case MGN_11M:  *rate_config |= RRSR_11M;       break;
2307                          case MGN_6M:   *rate_config |= RRSR_6M;        break;
2308                          case MGN_9M:   *rate_config |= RRSR_9M;        break;
2309                          case MGN_12M:  *rate_config |= RRSR_12M;       break;
2310                          case MGN_18M:  *rate_config |= RRSR_18M;       break;
2311                          case MGN_24M:  *rate_config |= RRSR_24M;       break;
2312                          case MGN_36M:  *rate_config |= RRSR_36M;       break;
2313                          case MGN_48M:  *rate_config |= RRSR_48M;       break;
2314                          case MGN_54M:  *rate_config |= RRSR_54M;       break;
2315                  }
2316          }
2317          for (i=0; i<net->rates_ex_len; i++)
2318          {
2319                  basic_rate = net->rates_ex[i]&0x7f;
2320                  switch(basic_rate)
2321                  {
2322                          case MGN_1M:   *rate_config |= RRSR_1M;        break;
2323                          case MGN_2M:   *rate_config |= RRSR_2M;        break;
2324                          case MGN_5_5M: *rate_config |= RRSR_5_5M;      break;
2325                          case MGN_11M:  *rate_config |= RRSR_11M;       break;
2326                          case MGN_6M:   *rate_config |= RRSR_6M;        break;
2327                          case MGN_9M:   *rate_config |= RRSR_9M;        break;
2328                          case MGN_12M:  *rate_config |= RRSR_12M;       break;
2329                          case MGN_18M:  *rate_config |= RRSR_18M;       break;
2330                          case MGN_24M:  *rate_config |= RRSR_24M;       break;
2331                          case MGN_36M:  *rate_config |= RRSR_36M;       break;
2332                          case MGN_48M:  *rate_config |= RRSR_48M;       break;
2333                          case MGN_54M:  *rate_config |= RRSR_54M;       break;
2334                  }
2335          }
2336 }
2337
2338
2339 #define SHORT_SLOT_TIME 9
2340 #define NON_SHORT_SLOT_TIME 20
2341
2342 void rtl8192_update_cap(struct net_device* dev, u16 cap)
2343 {
2344         //u32 tmp = 0;
2345         struct r8192_priv *priv = ieee80211_priv(dev);
2346         struct ieee80211_network *net = &priv->ieee80211->current_network;
2347         priv->short_preamble = cap & WLAN_CAPABILITY_SHORT_PREAMBLE;
2348
2349         //LZM MOD 090303 HW_VAR_ACK_PREAMBLE
2350 #ifdef RTL8192SU
2351         if(0)
2352         {
2353                 u8 tmp = 0;
2354                 tmp = ((priv->nCur40MhzPrimeSC) << 5);
2355                 if (priv->short_preamble)
2356                         tmp |= 0x80;
2357                 write_nic_byte(dev, RRSR+2, tmp);
2358         }
2359 #else
2360         {
2361         u32 tmp = 0;
2362         tmp = priv->basic_rate;
2363         if (priv->short_preamble)
2364                 tmp |= BRSR_AckShortPmb;
2365         write_nic_dword(dev, RRSR, tmp);
2366         }
2367 #endif
2368
2369         if (net->mode & (IEEE_G|IEEE_N_24G))
2370         {
2371                 u8 slot_time = 0;
2372                 if ((cap & WLAN_CAPABILITY_SHORT_SLOT)&&(!priv->ieee80211->pHTInfo->bCurrentRT2RTLongSlotTime))
2373                 {//short slot time
2374                         slot_time = SHORT_SLOT_TIME;
2375                 }
2376                 else //long slot time
2377                         slot_time = NON_SHORT_SLOT_TIME;
2378                 priv->slot_time = slot_time;
2379                 write_nic_byte(dev, SLOT_TIME, slot_time);
2380         }
2381
2382 }
2383 void rtl8192_net_update(struct net_device *dev)
2384 {
2385
2386         struct r8192_priv *priv = ieee80211_priv(dev);
2387         struct ieee80211_network *net;
2388         u16 BcnTimeCfg = 0, BcnCW = 6, BcnIFS = 0xf;
2389         u16 rate_config = 0;
2390         net = & priv->ieee80211->current_network;
2391
2392         rtl8192_config_rate(dev, &rate_config);
2393         priv->basic_rate = rate_config &= 0x15f;
2394
2395         write_nic_dword(dev,BSSIDR,((u32*)net->bssid)[0]);
2396         write_nic_word(dev,BSSIDR+4,((u16*)net->bssid)[2]);
2397         //for(i=0;i<ETH_ALEN;i++)
2398         //      write_nic_byte(dev,BSSID+i,net->bssid[i]);
2399
2400         rtl8192_update_msr(dev);
2401 //      rtl8192_update_cap(dev, net->capability);
2402         if (priv->ieee80211->iw_mode == IW_MODE_ADHOC)
2403         {
2404         write_nic_word(dev, ATIMWND, 2);
2405         write_nic_word(dev, BCN_DMATIME, 1023);
2406         write_nic_word(dev, BCN_INTERVAL, net->beacon_interval);
2407 //      write_nic_word(dev, BcnIntTime, 100);
2408         write_nic_word(dev, BCN_DRV_EARLY_INT, 1);
2409         write_nic_byte(dev, BCN_ERR_THRESH, 100);
2410                 BcnTimeCfg |= (BcnCW<<BCN_TCFG_CW_SHIFT);
2411         // TODO: BcnIFS may required to be changed on ASIC
2412                 BcnTimeCfg |= BcnIFS<<BCN_TCFG_IFS;
2413
2414         write_nic_word(dev, BCN_TCFG, BcnTimeCfg);
2415         }
2416
2417
2418
2419 }
2420
2421 //temporary hw beacon is not used any more.
2422 //open it when necessary
2423 #if 1
2424 void rtl819xusb_beacon_tx(struct net_device *dev,u16  tx_rate)
2425 {
2426
2427 #if 0
2428         struct r8192_priv *priv = ieee80211_priv(dev);
2429         struct sk_buff *skb;
2430         int i = 0;
2431         //u8 cr;
2432
2433         rtl8192_net_update(dev);
2434
2435         skb = ieee80211_get_beacon(priv->ieee80211);
2436                 if(!skb){
2437                         DMESG("not enought memory for allocating beacon");
2438                         return;
2439                 }
2440
2441
2442                 write_nic_byte(dev, BQREQ, read_nic_byte(dev, BQREQ) | (1<<7));
2443
2444                 i=0;
2445                 //while(!read_nic_byte(dev,BQREQ & (1<<7)))
2446                 while( (read_nic_byte(dev, BQREQ) & (1<<7)) == 0 )
2447                 {
2448                         msleep_interruptible_rtl(HZ/2);
2449                         if(i++ > 10){
2450                                 DMESGW("get stuck to wait HW beacon to be ready");
2451                                 return ;
2452                         }
2453                 }
2454         skb->cb[0] = NORM_PRIORITY;
2455         skb->cb[1] = 0; //morefragment = 0
2456         skb->cb[2] = ieeerate2rtlrate(tx_rate);
2457
2458         rtl8192_tx(dev,skb);
2459
2460 #endif
2461 }
2462 #endif
2463 inline u8 rtl8192_IsWirelessBMode(u16 rate)
2464 {
2465         if( ((rate <= 110) && (rate != 60) && (rate != 90)) || (rate == 220) )
2466                 return 1;
2467         else return 0;
2468 }
2469
2470 u16 N_DBPSOfRate(u16 DataRate);
2471
2472 u16 ComputeTxTime(
2473         u16             FrameLength,
2474         u16             DataRate,
2475         u8              bManagementFrame,
2476         u8              bShortPreamble
2477 )
2478 {
2479         u16     FrameTime;
2480         u16     N_DBPS;
2481         u16     Ceiling;
2482
2483         if( rtl8192_IsWirelessBMode(DataRate) )
2484         {
2485                 if( bManagementFrame || !bShortPreamble || DataRate == 10 )
2486                 {       // long preamble
2487                         FrameTime = (u16)(144+48+(FrameLength*8/(DataRate/10)));
2488                 }
2489                 else
2490                 {       // Short preamble
2491                         FrameTime = (u16)(72+24+(FrameLength*8/(DataRate/10)));
2492                 }
2493                 if( ( FrameLength*8 % (DataRate/10) ) != 0 ) //Get the Ceilling
2494                                 FrameTime ++;
2495         } else {        //802.11g DSSS-OFDM PLCP length field calculation.
2496                 N_DBPS = N_DBPSOfRate(DataRate);
2497                 Ceiling = (16 + 8*FrameLength + 6) / N_DBPS
2498                                 + (((16 + 8*FrameLength + 6) % N_DBPS) ? 1 : 0);
2499                 FrameTime = (u16)(16 + 4 + 4*Ceiling + 6);
2500         }
2501         return FrameTime;
2502 }
2503
2504 u16 N_DBPSOfRate(u16 DataRate)
2505 {
2506          u16 N_DBPS = 24;
2507
2508          switch(DataRate)
2509          {
2510          case 60:
2511           N_DBPS = 24;
2512           break;
2513
2514          case 90:
2515           N_DBPS = 36;
2516           break;
2517
2518          case 120:
2519           N_DBPS = 48;
2520           break;
2521
2522          case 180:
2523           N_DBPS = 72;
2524           break;
2525
2526          case 240:
2527           N_DBPS = 96;
2528           break;
2529
2530          case 360:
2531           N_DBPS = 144;
2532           break;
2533
2534          case 480:
2535           N_DBPS = 192;
2536           break;
2537
2538          case 540:
2539           N_DBPS = 216;
2540           break;
2541
2542          default:
2543           break;
2544          }
2545
2546          return N_DBPS;
2547 }
2548
2549 void rtl819xU_cmd_isr(struct urb *tx_cmd_urb, struct pt_regs *regs)
2550 {
2551 #if 0
2552         struct net_device *dev = (struct net_device*)tx_cmd_urb->context;
2553         struct r8192_priv *priv = ieee80211_priv(dev);
2554         int                last_init_packet = 0;
2555         u8                 *ptr_cmd_buf;
2556         u16                 cmd_buf_len;
2557
2558         if(tx_cmd_urb->status != 0) {
2559                 priv->pFirmware.firmware_seg_index = 0; //only begin transter, should it can be set to 1
2560         }
2561
2562         /* Free the urb and the corresponding buf for common Tx cmd packet, or
2563          * last segment of each firmware img.
2564          */
2565         if((priv->pFirmware.firmware_seg_index == 0) ||(priv->pFirmware.firmware_seg_index == priv->pFirmware.firmware_seg_maxnum)) {
2566                 priv->pFirmware.firmware_seg_index = 0;//only begin transter, should it can be set to 1
2567         } else {
2568                 /* prepare for last transfer */
2569                 /* update some infomation for */
2570                 /* last segment of the firmware img need indicate to device */
2571                 priv->pFirmware.firmware_seg_index++;
2572                 if(priv->pFirmware.firmware_seg_index == priv->pFirmware.firmware_seg_maxnum) {
2573                         last_init_packet = 1;
2574                 }
2575
2576                 cmd_buf_len = priv->pFirmware.firmware_seg_container[priv->pFirmware.firmware_seg_index-1].seg_size;
2577                 ptr_cmd_buf = priv->pFfirmware.firmware_seg_container[priv->pFfirmware.firmware_seg_index-1].seg_ptr;
2578                 rtl819xU_tx_cmd(dev, ptr_cmd_buf, cmd_buf_len, last_init_packet, DESC_PACKET_TYPE_INIT);
2579         }
2580
2581         kfree(tx_cmd_urb->transfer_buffer);
2582 #endif
2583         usb_free_urb(tx_cmd_urb);
2584 }
2585
2586 unsigned int txqueue2outpipe(struct r8192_priv* priv,unsigned int tx_queue) {
2587
2588         if(tx_queue >= 9)
2589         {
2590                 RT_TRACE(COMP_ERR,"%s():Unknown queue ID!!!\n",__FUNCTION__);
2591                 return 0x04;
2592         }
2593         return priv->txqueue_to_outpipemap[tx_queue];
2594 }
2595
2596 #ifdef RTL8192SU
2597 short rtl8192SU_tx_cmd(struct net_device *dev, struct sk_buff *skb)
2598 {
2599         struct r8192_priv *priv = ieee80211_priv(dev);
2600         int                     status;
2601         struct urb              *tx_urb;
2602         unsigned int            idx_pipe;
2603         tx_desc_cmd_819x_usb *pdesc = (tx_desc_cmd_819x_usb *)skb->data;
2604         cb_desc *tcb_desc = (cb_desc *)(skb->cb + MAX_DEV_ADDR_SIZE);
2605         u8 queue_index = tcb_desc->queue_index;
2606         u32                     PktSize = 0;
2607
2608         //printk("\n %s::::::::::::::::::::::queue_index = %d\n",__FUNCTION__, queue_index);
2609         atomic_inc(&priv->tx_pending[queue_index]);
2610
2611         tx_urb = usb_alloc_urb(0,GFP_ATOMIC);
2612         if(!tx_urb){
2613                 dev_kfree_skb(skb);
2614                 return -ENOMEM;
2615         }
2616
2617         memset(pdesc, 0, USB_HWDESC_HEADER_LEN);
2618
2619         /* Tx descriptor ought to be set according to the skb->cb */
2620         pdesc->LINIP = tcb_desc->bLastIniPkt;
2621         PktSize = (u16)(skb->len - USB_HWDESC_HEADER_LEN);
2622         pdesc->PktSize = PktSize;
2623         //printk("PKTSize = %d %x\n",pdesc->PktSize,pdesc->PktSize);
2624         //----------------------------------------------------------------------------
2625         // Fill up USB_OUT_CONTEXT.
2626         //----------------------------------------------------------------------------
2627         // Get index to out pipe from specified QueueID.
2628         idx_pipe = txqueue2outpipe(priv,queue_index);
2629         //printk("=============>%s queue_index:%d, outpipe:%d\n", __func__,queue_index,priv->RtOutPipes[idx_pipe]);
2630
2631 #ifdef JOHN_DUMP_TXDESC
2632         int i;
2633         printk("Len = %d\n", skb->len);
2634         for (i = 0; i < 8; i++)
2635                 printk("%2.2x ", *((u8*)skb->data+i));
2636         printk("\n");
2637 #endif
2638
2639         usb_fill_bulk_urb(tx_urb,
2640                                     priv->udev,
2641                                     usb_sndbulkpipe(priv->udev,priv->RtOutPipes[idx_pipe]),
2642                                     skb->data,
2643                                     skb->len,
2644                                     rtl8192_tx_isr,
2645                                     skb);
2646
2647         status = usb_submit_urb(tx_urb, GFP_ATOMIC);
2648         if (!status){
2649                 return 0;
2650         }else{
2651                 printk("Error TX CMD URB, error %d",
2652                                 status);
2653                 return -1;
2654         }
2655 }
2656 #else
2657 short rtl819xU_tx_cmd(struct net_device *dev, struct sk_buff *skb)
2658 {
2659         struct r8192_priv *priv = ieee80211_priv(dev);
2660         //u8                    *tx;
2661         int                     status;
2662         struct urb              *tx_urb;
2663         //int                   urb_buf_len;
2664         unsigned int            idx_pipe;
2665         tx_desc_cmd_819x_usb *pdesc = (tx_desc_cmd_819x_usb *)skb->data;
2666         cb_desc *tcb_desc = (cb_desc *)(skb->cb + MAX_DEV_ADDR_SIZE);
2667         u8 queue_index = tcb_desc->queue_index;
2668
2669         //printk("\n %s::queue_index = %d\n",__FUNCTION__, queue_index);
2670         atomic_inc(&priv->tx_pending[queue_index]);
2671
2672         tx_urb = usb_alloc_urb(0,GFP_ATOMIC);
2673         if(!tx_urb){
2674                 dev_kfree_skb(skb);
2675                 return -ENOMEM;
2676         }
2677
2678         memset(pdesc, 0, USB_HWDESC_HEADER_LEN);
2679         /* Tx descriptor ought to be set according to the skb->cb */
2680         pdesc->FirstSeg = 1;//bFirstSeg;
2681         pdesc->LastSeg = 1;//bLastSeg;
2682         pdesc->CmdInit = tcb_desc->bCmdOrInit;
2683         pdesc->TxBufferSize = tcb_desc->txbuf_size;
2684         pdesc->OWN = 1;
2685         pdesc->LINIP = tcb_desc->bLastIniPkt;
2686
2687         //----------------------------------------------------------------------------
2688         // Fill up USB_OUT_CONTEXT.
2689         //----------------------------------------------------------------------------
2690         // Get index to out pipe from specified QueueID.
2691         idx_pipe = txqueue2outpipe(priv,queue_index);
2692 #ifdef JOHN_DUMP_TXDESC
2693         int i;
2694         printk("<Tx descriptor>--rate %x---",rate);
2695         for (i = 0; i < 8; i++)
2696                 printk("%8x ", tx[i]);
2697         printk("\n");
2698 #endif
2699         usb_fill_bulk_urb(tx_urb,priv->udev, usb_sndbulkpipe(priv->udev,idx_pipe), \
2700                         skb->data, skb->len, rtl8192_tx_isr, skb);
2701
2702         status = usb_submit_urb(tx_urb, GFP_ATOMIC);
2703         if (!status){
2704                 return 0;
2705         }else{
2706                 DMESGE("Error TX CMD URB, error %d",
2707                                 status);
2708                 return -1;
2709         }
2710 }
2711 #endif
2712
2713 /*
2714  * Mapping Software/Hardware descriptor queue id to "Queue Select Field"
2715  * in TxFwInfo data structure
2716  * 2006.10.30 by Emily
2717  *
2718  * \param QUEUEID       Software Queue
2719 */
2720 u8 MapHwQueueToFirmwareQueue(u8 QueueID)
2721 {
2722         u8 QueueSelect = 0x0;       //defualt set to
2723
2724         switch(QueueID) {
2725                 case BE_QUEUE:
2726                         QueueSelect = QSLT_BE;  //or QSelect = pTcb->priority;
2727                         break;
2728
2729                 case BK_QUEUE:
2730                         QueueSelect = QSLT_BK;  //or QSelect = pTcb->priority;
2731                         break;
2732
2733                 case VO_QUEUE:
2734                         QueueSelect = QSLT_VO;  //or QSelect = pTcb->priority;
2735                         break;
2736
2737                 case VI_QUEUE:
2738                         QueueSelect = QSLT_VI;  //or QSelect = pTcb->priority;
2739                         break;
2740                 case MGNT_QUEUE:
2741                         QueueSelect = QSLT_MGNT;
2742                         break;
2743
2744                 case BEACON_QUEUE:
2745                         QueueSelect = QSLT_BEACON;
2746                         break;
2747
2748                         // TODO: 2006.10.30 mark other queue selection until we verify it is OK
2749                         // TODO: Remove Assertions
2750 //#if (RTL819X_FPGA_VER & RTL819X_FPGA_GUANGAN_070502)
2751                 case TXCMD_QUEUE:
2752                         QueueSelect = QSLT_CMD;
2753                         break;
2754 //#endif
2755                 case HIGH_QUEUE:
2756                         QueueSelect = QSLT_HIGH;
2757                         break;
2758
2759                 default:
2760                         RT_TRACE(COMP_ERR, "TransmitTCB(): Impossible Queue Selection: %d \n", QueueID);
2761                         break;
2762         }
2763         return QueueSelect;
2764 }
2765
2766 #ifdef RTL8192SU
2767 u8 MRateToHwRate8190Pci(u8 rate)
2768 {
2769         u8      ret = DESC92S_RATE1M;
2770
2771         switch(rate)
2772         {
2773                 // CCK and OFDM non-HT rates
2774         case MGN_1M:            ret = DESC92S_RATE1M;   break;
2775         case MGN_2M:            ret = DESC92S_RATE2M;   break;
2776         case MGN_5_5M:          ret = DESC92S_RATE5_5M; break;
2777         case MGN_11M:           ret = DESC92S_RATE11M;  break;
2778         case MGN_6M:            ret = DESC92S_RATE6M;   break;
2779         case MGN_9M:            ret = DESC92S_RATE9M;   break;
2780         case MGN_12M:           ret = DESC92S_RATE12M;  break;
2781         case MGN_18M:           ret = DESC92S_RATE18M;  break;
2782         case MGN_24M:           ret = DESC92S_RATE24M;  break;
2783         case MGN_36M:           ret = DESC92S_RATE36M;  break;
2784         case MGN_48M:           ret = DESC92S_RATE48M;  break;
2785         case MGN_54M:           ret = DESC92S_RATE54M;  break;
2786
2787                 // HT rates since here
2788         case MGN_MCS0:          ret = DESC92S_RATEMCS0; break;
2789         case MGN_MCS1:          ret = DESC92S_RATEMCS1; break;
2790         case MGN_MCS2:          ret = DESC92S_RATEMCS2; break;
2791         case MGN_MCS3:          ret = DESC92S_RATEMCS3; break;
2792         case MGN_MCS4:          ret = DESC92S_RATEMCS4; break;
2793         case MGN_MCS5:          ret = DESC92S_RATEMCS5; break;
2794         case MGN_MCS6:          ret = DESC92S_RATEMCS6; break;
2795         case MGN_MCS7:          ret = DESC92S_RATEMCS7; break;
2796         case MGN_MCS8:          ret = DESC92S_RATEMCS8; break;
2797         case MGN_MCS9:          ret = DESC92S_RATEMCS9; break;
2798         case MGN_MCS10: ret = DESC92S_RATEMCS10;        break;
2799         case MGN_MCS11: ret = DESC92S_RATEMCS11;        break;
2800         case MGN_MCS12: ret = DESC92S_RATEMCS12;        break;
2801         case MGN_MCS13: ret = DESC92S_RATEMCS13;        break;
2802         case MGN_MCS14: ret = DESC92S_RATEMCS14;        break;
2803         case MGN_MCS15: ret = DESC92S_RATEMCS15;        break;
2804
2805         // Set the highest SG rate
2806         case MGN_MCS0_SG:
2807         case MGN_MCS1_SG:
2808         case MGN_MCS2_SG:
2809         case MGN_MCS3_SG:
2810         case MGN_MCS4_SG:
2811         case MGN_MCS5_SG:
2812         case MGN_MCS6_SG:
2813         case MGN_MCS7_SG:
2814         case MGN_MCS8_SG:
2815         case MGN_MCS9_SG:
2816         case MGN_MCS10_SG:
2817         case MGN_MCS11_SG:
2818         case MGN_MCS12_SG:
2819         case MGN_MCS13_SG:
2820         case MGN_MCS14_SG:
2821         case MGN_MCS15_SG:
2822         {
2823                 ret = DESC92S_RATEMCS15_SG;
2824                 break;
2825         }
2826
2827         default:                break;
2828         }
2829         return ret;
2830 }
2831 #else
2832 u8 MRateToHwRate8190Pci(u8 rate)
2833 {
2834         u8  ret = DESC90_RATE1M;
2835
2836         switch(rate) {
2837                 case MGN_1M:    ret = DESC90_RATE1M;    break;
2838                 case MGN_2M:    ret = DESC90_RATE2M;    break;
2839                 case MGN_5_5M:  ret = DESC90_RATE5_5M;  break;
2840                 case MGN_11M:   ret = DESC90_RATE11M;   break;
2841                 case MGN_6M:    ret = DESC90_RATE6M;    break;
2842                 case MGN_9M:    ret = DESC90_RATE9M;    break;
2843                 case MGN_12M:   ret = DESC90_RATE12M;   break;
2844                 case MGN_18M:   ret = DESC90_RATE18M;   break;
2845                 case MGN_24M:   ret = DESC90_RATE24M;   break;
2846                 case MGN_36M:   ret = DESC90_RATE36M;   break;
2847                 case MGN_48M:   ret = DESC90_RATE48M;   break;
2848                 case MGN_54M:   ret = DESC90_RATE54M;   break;
2849
2850                 // HT rate since here
2851                 case MGN_MCS0:  ret = DESC90_RATEMCS0;  break;
2852                 case MGN_MCS1:  ret = DESC90_RATEMCS1;  break;
2853                 case MGN_MCS2:  ret = DESC90_RATEMCS2;  break;
2854                 case MGN_MCS3:  ret = DESC90_RATEMCS3;  break;
2855                 case MGN_MCS4:  ret = DESC90_RATEMCS4;  break;
2856                 case MGN_MCS5:  ret = DESC90_RATEMCS5;  break;
2857                 case MGN_MCS6:  ret = DESC90_RATEMCS6;  break;
2858                 case MGN_MCS7:  ret = DESC90_RATEMCS7;  break;
2859                 case MGN_MCS8:  ret = DESC90_RATEMCS8;  break;
2860                 case MGN_MCS9:  ret = DESC90_RATEMCS9;  break;
2861                 case MGN_MCS10: ret = DESC90_RATEMCS10; break;
2862                 case MGN_MCS11: ret = DESC90_RATEMCS11; break;
2863                 case MGN_MCS12: ret = DESC90_RATEMCS12; break;
2864                 case MGN_MCS13: ret = DESC90_RATEMCS13; break;
2865                 case MGN_MCS14: ret = DESC90_RATEMCS14; break;
2866                 case MGN_MCS15: ret = DESC90_RATEMCS15; break;
2867                 case (0x80|0x20): ret = DESC90_RATEMCS32; break;
2868
2869                 default:       break;
2870         }
2871         return ret;
2872 }
2873 #endif
2874
2875 u8 QueryIsShort(u8 TxHT, u8 TxRate, cb_desc *tcb_desc)
2876 {
2877         u8   tmp_Short;
2878
2879         tmp_Short = (TxHT==1)?((tcb_desc->bUseShortGI)?1:0):((tcb_desc->bUseShortPreamble)?1:0);
2880
2881         if(TxHT==1 && TxRate != DESC90_RATEMCS15)
2882                 tmp_Short = 0;
2883
2884         return tmp_Short;
2885 }
2886
2887 static void tx_zero_isr(struct urb *tx_urb)
2888 {
2889         return;
2890 }
2891
2892
2893 #ifdef RTL8192SU
2894 /*
2895  * The tx procedure is just as following,  skb->cb will contain all the following
2896  *information: * priority, morefrag, rate, &dev.
2897  * */
2898  //     <Note> Buffer format for 8192S Usb bulk out:
2899 //
2900 //  --------------------------------------------------
2901 //  | 8192S Usb Tx Desc | 802_11_MAC_header |    data          |
2902 //  --------------------------------------------------
2903 //  |  32 bytes                   |       24 bytes             |0-2318 bytes|
2904 //  --------------------------------------------------
2905 //  |<------------ BufferLen ------------------------->|
2906
2907 short rtl8192SU_tx(struct net_device *dev, struct sk_buff* skb)
2908 {
2909         struct r8192_priv *priv = ieee80211_priv(dev);
2910         cb_desc *tcb_desc = (cb_desc *)(skb->cb + MAX_DEV_ADDR_SIZE);
2911         tx_desc_819x_usb *tx_desc = (tx_desc_819x_usb *)skb->data;
2912         //tx_fwinfo_819x_usb *tx_fwinfo = (tx_fwinfo_819x_usb *)(skb->data + USB_HWDESC_HEADER_LEN);//92su del
2913         struct usb_device *udev = priv->udev;
2914         int pend;
2915         int status;
2916         struct urb *tx_urb = NULL, *tx_urb_zero = NULL;
2917         //int urb_len;
2918         unsigned int idx_pipe;
2919         u16             MPDUOverhead = 0;
2920         //RT_DEBUG_DATA(COMP_SEND, tcb_desc, sizeof(cb_desc));
2921
2922 #if 0
2923         /* Added by Annie for filling Len_Adjust field. 2005-12-14. */
2924         RT_ENC_ALG  EncAlg = NO_Encryption;
2925 #endif
2926
2927
2928         pend = atomic_read(&priv->tx_pending[tcb_desc->queue_index]);
2929         /* we are locked here so the two atomic_read and inc are executed
2930          * without interleaves  * !!! For debug purpose           */
2931         if( pend > MAX_TX_URB){
2932                 switch (tcb_desc->queue_index) {
2933                         case VO_PRIORITY:
2934                                 priv->stats.txvodrop++;
2935                                 break;
2936                         case VI_PRIORITY:
2937                                 priv->stats.txvidrop++;
2938                                 break;
2939                         case BE_PRIORITY:
2940                                 priv->stats.txbedrop++;
2941                                 break;
2942                         default://BK_PRIORITY
2943                                 priv->stats.txbkdrop++;
2944                                 break;
2945                 }
2946                 printk("To discard skb packet!\n");
2947                 dev_kfree_skb_any(skb);
2948                 return -1;
2949         }
2950
2951         tx_urb = usb_alloc_urb(0,GFP_ATOMIC);
2952         if(!tx_urb){
2953                 dev_kfree_skb_any(skb);
2954                 return -ENOMEM;
2955         }
2956
2957         memset(tx_desc, 0, sizeof(tx_desc_819x_usb));
2958
2959
2960 #if (defined (RTL8192SU_FPGA_2MAC_VERIFICATION)||defined (RTL8192SU_ASIC_VERIFICATION))
2961                 tx_desc->NonQos = (IsQoSDataFrame(skb->data)==TRUE)? 0:1;
2962 #endif
2963
2964         /* Fill Tx descriptor */
2965         //memset(tx_fwinfo,0,sizeof(tx_fwinfo_819x_usb));
2966
2967         // This part can just fill to the first descriptor of the frame.
2968         /* DWORD 0 */
2969         tx_desc->TxHT = (tcb_desc->data_rate&0x80)?1:0;
2970
2971
2972         tx_desc->TxRate = MRateToHwRate8190Pci(tcb_desc->data_rate);
2973         //tx_desc->EnableCPUDur = tcb_desc->bTxEnableFwCalcDur;
2974         tx_desc->TxShort = QueryIsShort(tx_desc->TxHT, tx_desc->TxRate, tcb_desc);
2975
2976
2977         // Aggregation related
2978         if(tcb_desc->bAMPDUEnable) {//AMPDU enabled
2979                 tx_desc->AllowAggregation = 1;
2980                 /* DWORD 1 */
2981                 //tx_fwinfo->RxMF = tcb_desc->ampdu_factor;
2982                 //tx_fwinfo->RxAMD = tcb_desc->ampdu_density&0x07;//ampdudensity
2983         } else {
2984                 tx_desc->AllowAggregation = 0;
2985                 /* DWORD 1 */
2986                 //tx_fwinfo->RxMF = 0;
2987                 //tx_fwinfo->RxAMD = 0;
2988         }
2989
2990         //
2991         // <Roger_Notes> For AMPDU case, we must insert SSN into TX_DESC,
2992         // FW according as this SSN to do necessary packet retry.
2993         // 2008.06.06.
2994         //
2995         {
2996                 u8      *pSeq;
2997                 u16     Temp;
2998                 //pSeq = (u8 *)(VirtualAddress+USB_HWDESC_HEADER_LEN + FRAME_OFFSET_SEQUENCE);
2999                 pSeq = (u8 *)(skb->data+USB_HWDESC_HEADER_LEN + 22);
3000                 Temp = pSeq[0];
3001                 Temp <<= 12;
3002                 Temp |= (*(u16 *)pSeq)>>4;
3003                 tx_desc->Seq = Temp;
3004         }
3005
3006         /* Protection mode related */
3007         tx_desc->RTSEn = (tcb_desc->bRTSEnable)?1:0;
3008         tx_desc->CTS2Self = (tcb_desc->bCTSEnable)?1:0;
3009         tx_desc->RTSSTBC = (tcb_desc->bRTSSTBC)?1:0;
3010         tx_desc->RTSHT = (tcb_desc->rts_rate&0x80)?1:0;
3011         tx_desc->RTSRate =  MRateToHwRate8190Pci((u8)tcb_desc->rts_rate);
3012         tx_desc->RTSSubcarrier = (tx_desc->RTSHT==0)?(tcb_desc->RTSSC):0;
3013         tx_desc->RTSBW = (tx_desc->RTSHT==1)?((tcb_desc->bRTSBW)?1:0):0;
3014         tx_desc->RTSShort = (tx_desc->RTSHT==0)?(tcb_desc->bRTSUseShortPreamble?1:0):\
3015                                 (tcb_desc->bRTSUseShortGI?1:0);
3016         //LZM 090219
3017         tx_desc->DisRTSFB = 0;
3018         tx_desc->RTSRateFBLmt = 0xf;
3019
3020         // <Roger_EXP> 2008.09.22. We disable RTS rate fallback temporarily.
3021         //tx_desc->DisRTSFB = 0x01;
3022
3023         /* Set Bandwidth and sub-channel settings. */
3024         if(priv->CurrentChannelBW == HT_CHANNEL_WIDTH_20_40)
3025         {
3026                 if(tcb_desc->bPacketBW) {
3027                         tx_desc->TxBandwidth = 1;
3028                         tx_desc->TxSubCarrier = 0;    //By SD3's Jerry suggestion, use duplicated mode
3029                 } else {
3030                         tx_desc->TxBandwidth = 0;
3031                         tx_desc->TxSubCarrier = priv->nCur40MhzPrimeSC;
3032                 }
3033         } else {
3034                 tx_desc->TxBandwidth = 0;
3035                 tx_desc->TxSubCarrier = 0;
3036         }
3037
3038
3039         //memset(tx_desc, 0, sizeof(tx_desc_819x_usb));
3040         /* DWORD 0 */
3041         tx_desc->LINIP = 0;
3042         //tx_desc->CmdInit = 1; //92su del
3043         tx_desc->Offset =  USB_HWDESC_HEADER_LEN;
3044
3045         {
3046                 tx_desc->PktSize = (skb->len - USB_HWDESC_HEADER_LEN) & 0xffff;
3047         }
3048
3049         /*DWORD 1*/
3050         //tx_desc->SecCAMID= 0;//92su del
3051         tx_desc->RaBRSRID= tcb_desc->RATRIndex;
3052 //#ifdef RTL8192S_PREPARE_FOR_NORMAL_RELEASE
3053 #if 0//LZM 090219
3054         tx_desc->RaBRSRID= 1;
3055 #endif
3056
3057 #if 0
3058         /* Fill security related */
3059         if( pTcb->bEncrypt && !Adapter->MgntInfo.SecurityInfo.SWTxEncryptFlag)
3060         {
3061                 EncAlg = SecGetEncryptionOverhead(
3062                                 Adapter,
3063                                 &EncryptionMPDUHeadOverhead,
3064                                 &EncryptionMPDUTailOverhead,
3065                                 NULL,
3066                                 NULL,
3067                                 FALSE,
3068                                 FALSE);
3069                 //2004/07/22, kcwu, EncryptionMPDUHeadOverhead has been added in previous code
3070                 //MPDUOverhead = EncryptionMPDUHeadOverhead + EncryptionMPDUTailOverhead;
3071                 MPDUOverhead = EncryptionMPDUTailOverhead;
3072                 tx_desc->NoEnc = 0;
3073                 RT_TRACE(COMP_SEC, DBG_LOUD, ("******We in the loop SecCAMID is %d SecDescAssign is %d The Sec is %d********\n",tx_desc->SecCAMID,tx_desc->SecDescAssign,EncAlg));
3074                 //CamDumpAll(Adapter);
3075         }
3076         else
3077 #endif
3078         {
3079                 MPDUOverhead = 0;
3080                 //tx_desc->NoEnc = 1;//92su del
3081         }
3082 #if 0
3083         switch(EncAlg){
3084                 case NO_Encryption:
3085                         tx_desc->SecType = 0x0;
3086                         break;
3087                 case WEP40_Encryption:
3088                 case WEP104_Encryption:
3089                         tx_desc->SecType = 0x1;
3090                         break;
3091                 case TKIP_Encryption:
3092                         tx_desc->SecType = 0x2;
3093                         break;
3094                 case AESCCMP_Encryption:
3095                         tx_desc->SecType = 0x3;
3096                         break;
3097                 default:
3098                         tx_desc->SecType = 0x0;
3099                         break;
3100         }
3101 #else
3102         tx_desc->SecType = 0x0;
3103 #endif
3104                 if (tcb_desc->bHwSec)
3105                         {
3106                                 switch (priv->ieee80211->pairwise_key_type)
3107                                 {
3108                                         case KEY_TYPE_WEP40:
3109                                         case KEY_TYPE_WEP104:
3110                                                  tx_desc->SecType = 0x1;
3111                                                  //tx_desc->NoEnc = 0;//92su del
3112                                                  break;
3113                                         case KEY_TYPE_TKIP:
3114                                                  tx_desc->SecType = 0x2;
3115                                                  //tx_desc->NoEnc = 0;//92su del
3116                                                  break;
3117                                         case KEY_TYPE_CCMP:
3118                                                  tx_desc->SecType = 0x3;
3119                                                  //tx_desc->NoEnc = 0;//92su del
3120                                                  break;
3121                                         case KEY_TYPE_NA:
3122                                                  tx_desc->SecType = 0x0;
3123                                                  //tx_desc->NoEnc = 1;//92su del
3124                                                  break;
3125                                         default:
3126                                                  tx_desc->SecType = 0x0;
3127                                                  //tx_desc->NoEnc = 1;//92su del
3128                                                  break;
3129                                 }
3130                         }
3131
3132         //tx_desc->TxFWInfoSize =  sizeof(tx_fwinfo_819x_usb);//92su del
3133
3134
3135         tx_desc->USERATE = tcb_desc->bTxUseDriverAssingedRate;
3136         tx_desc->DISFB = tcb_desc->bTxDisableRateFallBack;
3137         tx_desc->DataRateFBLmt = 0x1F;// Alwasy enable all rate fallback range
3138
3139         tx_desc->QueueSelect = MapHwQueueToFirmwareQueue(tcb_desc->queue_index);
3140
3141
3142         /* Fill fields that are required to be initialized in all of the descriptors */
3143         //DWORD 0
3144 #if 0
3145         tx_desc->FirstSeg = (tcb_desc->bFirstSeg)? 1:0;
3146         tx_desc->LastSeg = (tcb_desc->bLastSeg)?1:0;
3147 #else
3148         tx_desc->FirstSeg = 1;
3149         tx_desc->LastSeg = 1;
3150 #endif
3151         tx_desc->OWN = 1;
3152
3153         {
3154                 //DWORD 2
3155                 //tx_desc->TxBufferSize = (u32)(skb->len - USB_HWDESC_HEADER_LEN);
3156                 tx_desc->TxBufferSize = (u32)(skb->len);//92su mod FIXLZM
3157         }
3158
3159 #if 0
3160         RT_TRACE(COMP_FPGA, DBG_LOUD, ("(1)TxFillDescriptor8192SUsb(): DataRate(%#x)\n", pTcb->DataRate));
3161         RT_TRACE(COMP_FPGA, DBG_LOUD, ("(2)TxFillDescriptor8192SUsb(): bTxUseDriverAssingedRate(%#x)\n", pTcb->bTxUseDriverAssingedRate));
3162         RT_TRACE(COMP_FPGA, DBG_LOUD, ("(3)TxFillDescriptor8192SUsb(): bAMPDUEnable(%d)\n", pTcb->bAMPDUEnable));
3163         RT_TRACE(COMP_FPGA, DBG_LOUD, ("(4)TxFillDescriptor8192SUsb(): bRTSEnable(%d)\n", pTcb->bRTSEnable));
3164         RT_TRACE(COMP_FPGA, DBG_LOUD, ("(5)TxFillDescriptor8192SUsb(): RTSRate(%#x)\n", pTcb->RTSRate));
3165         RT_TRACE(COMP_FPGA, DBG_LOUD, ("(6)TxFillDescriptor8192SUsb(): bCTSEnable(%d)\n", pTcb->bCTSEnable));
3166         RT_TRACE(COMP_FPGA, DBG_LOUD, ("(7)TxFillDescriptor8192SUsb(): bUseShortGI(%d)\n", pTcb->bUseShortGI));
3167         RT_TRACE(COMP_FPGA, DBG_LOUD, ("(8)TxFillDescriptor8192SUsb(): bPacketBW(%d)\n", pTcb->bPacketBW));
3168         RT_TRACE(COMP_FPGA, DBG_LOUD, ("(9)TxFillDescriptor8192SUsb(): CurrentChannelBW(%d)\n", pHalData->CurrentChannelBW));
3169         RT_TRACE(COMP_FPGA, DBG_LOUD, ("(10)TxFillDescriptor8192SUsb(): bTxDisableRateFallBack(%d)\n", pTcb->bTxDisableRateFallBack));
3170         RT_TRACE(COMP_FPGA, DBG_LOUD, ("(11)TxFillDescriptor8192SUsb(): RATRIndex(%d)\n", pTcb->RATRIndex));
3171 #endif
3172
3173         /* Get index to out pipe from specified QueueID */
3174         idx_pipe = txqueue2outpipe(priv,tcb_desc->queue_index);
3175         //printk("=============>%s queue_index:%d, outpipe:%d\n", __func__,tcb_desc->queue_index,priv->RtOutPipes[idx_pipe]);
3176
3177         //RT_DEBUG_DATA(COMP_SEND,tx_fwinfo,sizeof(tx_fwinfo_819x_usb));
3178         //RT_DEBUG_DATA(COMP_SEND,tx_desc,sizeof(tx_desc_819x_usb));
3179
3180         /* To submit bulk urb */
3181         usb_fill_bulk_urb(tx_urb,
3182                                     udev,
3183                                     usb_sndbulkpipe(udev,priv->RtOutPipes[idx_pipe]),
3184                                     skb->data,
3185                                     skb->len, rtl8192_tx_isr, skb);
3186
3187         status = usb_submit_urb(tx_urb, GFP_ATOMIC);
3188         if (!status){
3189 //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
3190                 bool bSend0Byte = false;
3191                 u8 zero = 0;
3192                 if(udev->speed == USB_SPEED_HIGH)
3193                 {
3194                         if (skb->len > 0 && skb->len % 512 == 0)
3195                                 bSend0Byte = true;
3196                 }
3197                 else
3198                 {
3199                         if (skb->len > 0 && skb->len % 64 == 0)
3200                                 bSend0Byte = true;
3201                 }
3202                 if (bSend0Byte)
3203                 {
3204 #if 1
3205                         tx_urb_zero = usb_alloc_urb(0,GFP_ATOMIC);
3206                         if(!tx_urb_zero){
3207                                 RT_TRACE(COMP_ERR, "can't alloc urb for zero byte\n");
3208                                 return -ENOMEM;
3209                         }
3210                         usb_fill_bulk_urb(tx_urb_zero,udev,
3211                                         usb_sndbulkpipe(udev,idx_pipe), &zero,
3212                                         0, tx_zero_isr, dev);
3213                         status = usb_submit_urb(tx_urb_zero, GFP_ATOMIC);
3214                         if (status){
3215                         RT_TRACE(COMP_ERR, "Error TX URB for zero byte %d, error %d", atomic_read(&priv->tx_pending[tcb_desc->queue_index]), status);
3216                         return -1;
3217                         }
3218 #endif
3219                 }
3220                 dev->trans_start = jiffies;
3221                 atomic_inc(&priv->tx_pending[tcb_desc->queue_index]);
3222                 return 0;
3223         }else{
3224                 RT_TRACE(COMP_ERR, "Error TX URB %d, error %d", atomic_read(&priv->tx_pending[tcb_desc->queue_index]),
3225                                 status);
3226                 return -1;
3227         }
3228 }
3229 #else
3230
3231 /*
3232  * The tx procedure is just as following,
3233  * skb->cb will contain all the following information,
3234  * priority, morefrag, rate, &dev.
3235  * */
3236 short rtl8192_tx(struct net_device *dev, struct sk_buff* skb)
3237 {
3238         struct r8192_priv *priv = ieee80211_priv(dev);
3239         cb_desc *tcb_desc = (cb_desc *)(skb->cb + MAX_DEV_ADDR_SIZE);
3240         tx_desc_819x_usb *tx_desc = (tx_desc_819x_usb *)skb->data;
3241         tx_fwinfo_819x_usb *tx_fwinfo = (tx_fwinfo_819x_usb *)(skb->data + USB_HWDESC_HEADER_LEN);
3242         struct usb_device *udev = priv->udev;
3243         int pend;
3244         int status;
3245         struct urb *tx_urb = NULL, *tx_urb_zero = NULL;
3246         //int urb_len;
3247         unsigned int idx_pipe;
3248 //      RT_DEBUG_DATA(COMP_SEND, tcb_desc, sizeof(cb_desc));
3249 #if 0
3250         /* Added by Annie for filling Len_Adjust field. 2005-12-14. */
3251         RT_ENC_ALG  EncAlg = NO_Encryption;
3252 #endif
3253 //      printk("=============> %s\n", __FUNCTION__);
3254         pend = atomic_read(&priv->tx_pending[tcb_desc->queue_index]);
3255         /* we are locked here so the two atomic_read and inc are executed
3256          * without interleaves
3257          * !!! For debug purpose
3258          */
3259         if( pend > MAX_TX_URB){
3260 #if 0
3261                 switch (tcb_desc->queue_index) {
3262                         case VO_PRIORITY:
3263                                 priv->stats.txvodrop++;
3264                                 break;
3265                         case VI_PRIORITY:
3266                                 priv->stats.txvidrop++;
3267                                 break;
3268                         case BE_PRIORITY:
3269                                 priv->stats.txbedrop++;
3270                                 break;
3271                         default://BK_PRIORITY
3272                                 priv->stats.txbkdrop++;
3273                                 break;
3274                 }
3275 #endif
3276                 printk("To discard skb packet!\n");
3277                 dev_kfree_skb_any(skb);
3278                 return -1;
3279         }
3280
3281         tx_urb = usb_alloc_urb(0,GFP_ATOMIC);
3282         if(!tx_urb){
3283                 dev_kfree_skb_any(skb);
3284                 return -ENOMEM;
3285         }
3286
3287         /* Fill Tx firmware info */
3288         memset(tx_fwinfo,0,sizeof(tx_fwinfo_819x_usb));
3289         /* DWORD 0 */
3290         tx_fwinfo->TxHT = (tcb_desc->data_rate&0x80)?1:0;
3291         tx_fwinfo->TxRate = MRateToHwRate8190Pci(tcb_desc->data_rate);
3292         tx_fwinfo->EnableCPUDur = tcb_desc->bTxEnableFwCalcDur;
3293         tx_fwinfo->Short = QueryIsShort(tx_fwinfo->TxHT, tx_fwinfo->TxRate, tcb_desc);
3294         if(tcb_desc->bAMPDUEnable) {//AMPDU enabled
3295                 tx_fwinfo->AllowAggregation = 1;
3296                 /* DWORD 1 */
3297                 tx_fwinfo->RxMF = tcb_desc->ampdu_factor;
3298                 tx_fwinfo->RxAMD = tcb_desc->ampdu_density&0x07;//ampdudensity
3299         } else {
3300                 tx_fwinfo->AllowAggregation = 0;
3301                 /* DWORD 1 */
3302                 tx_fwinfo->RxMF = 0;
3303                 tx_fwinfo->RxAMD = 0;
3304         }
3305
3306         /* Protection mode related */
3307         tx_fwinfo->RtsEnable = (tcb_desc->bRTSEnable)?1:0;
3308         tx_fwinfo->CtsEnable = (tcb_desc->bCTSEnable)?1:0;
3309         tx_fwinfo->RtsSTBC = (tcb_desc->bRTSSTBC)?1:0;
3310         tx_fwinfo->RtsHT = (tcb_desc->rts_rate&0x80)?1:0;
3311         tx_fwinfo->RtsRate =  MRateToHwRate8190Pci((u8)tcb_desc->rts_rate);
3312         tx_fwinfo->RtsSubcarrier = (tx_fwinfo->RtsHT==0)?(tcb_desc->RTSSC):0;
3313         tx_fwinfo->RtsBandwidth = (tx_fwinfo->RtsHT==1)?((tcb_desc->bRTSBW)?1:0):0;
3314         tx_fwinfo->RtsShort = (tx_fwinfo->RtsHT==0)?(tcb_desc->bRTSUseShortPreamble?1:0):\
3315                                 (tcb_desc->bRTSUseShortGI?1:0);
3316
3317         /* Set Bandwidth and sub-channel settings. */
3318         if(priv->CurrentChannelBW == HT_CHANNEL_WIDTH_20_40)
3319         {
3320                 if(tcb_desc->bPacketBW) {
3321                         tx_fwinfo->TxBandwidth = 1;
3322                         tx_fwinfo->TxSubCarrier = 0;    //By SD3's Jerry suggestion, use duplicated mode
3323                 } else {
3324                         tx_fwinfo->TxBandwidth = 0;
3325                         tx_fwinfo->TxSubCarrier = priv->nCur40MhzPrimeSC;
3326                 }
3327         } else {
3328                 tx_fwinfo->TxBandwidth = 0;
3329                 tx_fwinfo->TxSubCarrier = 0;
3330         }
3331
3332         /* Fill Tx descriptor */
3333         memset(tx_desc, 0, sizeof(tx_desc_819x_usb));
3334         /* DWORD 0 */
3335         tx_desc->LINIP = 0;
3336         tx_desc->CmdInit = 1;
3337         tx_desc->Offset =  sizeof(tx_fwinfo_819x_usb) + 8;
3338
3339         {
3340                 tx_desc->PktSize = (skb->len - TX_PACKET_SHIFT_BYTES) & 0xffff;
3341         }
3342
3343         /*DWORD 1*/
3344         tx_desc->SecCAMID= 0;
3345         tx_desc->RATid = tcb_desc->RATRIndex;
3346 #if 0
3347         /* Fill security related */
3348         if( pTcb->bEncrypt && !Adapter->MgntInfo.SecurityInfo.SWTxEncryptFlag)
3349         {
3350                 EncAlg = SecGetEncryptionOverhead(
3351                                 Adapter,
3352                                 &EncryptionMPDUHeadOverhead,
3353                                 &EncryptionMPDUTailOverhead,
3354                                 NULL,
3355                                 NULL,
3356                                 FALSE,
3357                                 FALSE);
3358                 //2004/07/22, kcwu, EncryptionMPDUHeadOverhead has been added in previous code
3359                 //MPDUOverhead = EncryptionMPDUHeadOverhead + EncryptionMPDUTailOverhead;
3360                 MPDUOverhead = EncryptionMPDUTailOverhead;
3361                 tx_desc->NoEnc = 0;
3362                 RT_TRACE(COMP_SEC, DBG_LOUD, ("******We in the loop SecCAMID is %d SecDescAssign is %d The Sec is %d********\n",tx_desc->SecCAMID,tx_desc->SecDescAssign,EncAlg));
3363                 //CamDumpAll(Adapter);
3364         }
3365         else
3366 #endif
3367         {
3368                 //MPDUOverhead = 0;
3369                 tx_desc->NoEnc = 1;
3370         }
3371 #if 0
3372         switch(EncAlg){
3373                 case NO_Encryption:
3374                         tx_desc->SecType = 0x0;
3375                         break;
3376                 case WEP40_Encryption:
3377                 case WEP104_Encryption:
3378                         tx_desc->SecType = 0x1;
3379                         break;
3380                 case TKIP_Encryption:
3381                         tx_desc->SecType = 0x2;
3382                         break;
3383                 case AESCCMP_Encryption:
3384                         tx_desc->SecType = 0x3;
3385                         break;
3386                 default:
3387                         tx_desc->SecType = 0x0;
3388                         break;
3389         }
3390 #else
3391         tx_desc->SecType = 0x0;
3392 #endif
3393                 if (tcb_desc->bHwSec)
3394                         {
3395                                 switch (priv->ieee80211->pairwise_key_type)
3396                                 {
3397                                         case KEY_TYPE_WEP40:
3398                                         case KEY_TYPE_WEP104:
3399                                                  tx_desc->SecType = 0x1;
3400                                                  tx_desc->NoEnc = 0;
3401                                                  break;
3402                                         case KEY_TYPE_TKIP:
3403                                                  tx_desc->SecType = 0x2;
3404                                                  tx_desc->NoEnc = 0;
3405                                                  break;
3406                                         case KEY_TYPE_CCMP:
3407                                                  tx_desc->SecType = 0x3;
3408                                                  tx_desc->NoEnc = 0;
3409                                                  break;
3410                                         case KEY_TYPE_NA:
3411                                                  tx_desc->SecType = 0x0;
3412                                                  tx_desc->NoEnc = 1;
3413                                                  break;
3414                                 }
3415                         }
3416
3417         tx_desc->QueueSelect = MapHwQueueToFirmwareQueue(tcb_desc->queue_index);
3418         tx_desc->TxFWInfoSize =  sizeof(tx_fwinfo_819x_usb);
3419
3420         tx_desc->DISFB = tcb_desc->bTxDisableRateFallBack;
3421         tx_desc->USERATE = tcb_desc->bTxUseDriverAssingedRate;
3422
3423         /* Fill fields that are required to be initialized in all of the descriptors */
3424         //DWORD 0
3425 #if 0
3426         tx_desc->FirstSeg = (tcb_desc->bFirstSeg)? 1:0;
3427         tx_desc->LastSeg = (tcb_desc->bLastSeg)?1:0;
3428 #else
3429         tx_desc->FirstSeg = 1;
3430         tx_desc->LastSeg = 1;
3431 #endif
3432         tx_desc->OWN = 1;
3433
3434         {
3435                 //DWORD 2
3436                 tx_desc->TxBufferSize = (u32)(skb->len - USB_HWDESC_HEADER_LEN);
3437         }
3438         /* Get index to out pipe from specified QueueID */
3439         idx_pipe = txqueue2outpipe(priv,tcb_desc->queue_index);
3440
3441         //RT_DEBUG_DATA(COMP_SEND,tx_fwinfo,sizeof(tx_fwinfo_819x_usb));
3442         //RT_DEBUG_DATA(COMP_SEND,tx_desc,sizeof(tx_desc_819x_usb));
3443
3444         /* To submit bulk urb */
3445         usb_fill_bulk_urb(tx_urb,udev,
3446                         usb_sndbulkpipe(udev,idx_pipe), skb->data,
3447                         skb->len, rtl8192_tx_isr, skb);
3448
3449         status = usb_submit_urb(tx_urb, GFP_ATOMIC);
3450         if (!status){
3451 //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
3452                 bool bSend0Byte = false;
3453                 u8 zero = 0;
3454                 if(udev->speed == USB_SPEED_HIGH)
3455                 {
3456                         if (skb->len > 0 && skb->len % 512 == 0)
3457                                 bSend0Byte = true;
3458                 }
3459                 else
3460                 {
3461                         if (skb->len > 0 && skb->len % 64 == 0)
3462                                 bSend0Byte = true;
3463                 }
3464                 if (bSend0Byte)
3465                 {
3466 #if 1
3467                         tx_urb_zero = usb_alloc_urb(0,GFP_ATOMIC);
3468                         if(!tx_urb_zero){
3469                                 RT_TRACE(COMP_ERR, "can't alloc urb for zero byte\n");
3470                                 return -ENOMEM;
3471                         }
3472                         usb_fill_bulk_urb(tx_urb_zero,udev,
3473                                         usb_sndbulkpipe(udev,idx_pipe), &zero,
3474                                         0, tx_zero_isr, dev);
3475                         status = usb_submit_urb(tx_urb_zero, GFP_ATOMIC);
3476                         if (status){
3477                         RT_TRACE(COMP_ERR, "Error TX URB for zero byte %d, error %d", atomic_read(&priv->tx_pending[tcb_desc->queue_index]), status);
3478                         return -1;
3479                         }
3480 #endif
3481                 }
3482                 dev->trans_start = jiffies;
3483                 atomic_inc(&priv->tx_pending[tcb_desc->queue_index]);
3484                 return 0;
3485         }else{
3486                 RT_TRACE(COMP_ERR, "Error TX URB %d, error %d", atomic_read(&priv->tx_pending[tcb_desc->queue_index]),
3487                                 status);
3488                 return -1;
3489         }
3490 }
3491 #endif
3492
3493 #if 0
3494 void rtl8192_set_rate(struct net_device *dev)
3495 {
3496         int i;
3497         u16 word;
3498         int basic_rate,min_rr_rate,max_rr_rate;
3499
3500 //      struct r8192_priv *priv = ieee80211_priv(dev);
3501
3502         //if (ieee80211_is_54g(priv->ieee80211->current_network) &&
3503 //              priv->ieee80211->state == IEEE80211_LINKED){
3504         basic_rate = ieeerate2rtlrate(240);
3505         min_rr_rate = ieeerate2rtlrate(60);
3506         max_rr_rate = ieeerate2rtlrate(240);
3507
3508 //
3509 //      }else{
3510 //              basic_rate = ieeerate2rtlrate(20);
3511 //              min_rr_rate = ieeerate2rtlrate(10);
3512 //              max_rr_rate = ieeerate2rtlrate(110);
3513 //      }
3514
3515         write_nic_byte(dev, RESP_RATE,
3516                         max_rr_rate<<MAX_RESP_RATE_SHIFT| min_rr_rate<<MIN_RESP_RATE_SHIFT);
3517
3518         //word  = read_nic_word(dev, BRSR);
3519         word  = read_nic_word(dev, BRSR_8187);
3520         word &= ~BRSR_MBR_8185;
3521
3522
3523         for(i=0;i<=basic_rate;i++)
3524                 word |= (1<<i);
3525
3526         //write_nic_word(dev, BRSR, word);
3527         write_nic_word(dev, BRSR_8187, word);
3528         //DMESG("RR:%x BRSR: %x", read_nic_byte(dev,RESP_RATE), read_nic_word(dev,BRSR));
3529 }
3530 #endif
3531
3532
3533 #ifdef RTL8192SU
3534 void rtl8192SU_net_update(struct net_device *dev)
3535 {
3536
3537         struct r8192_priv *priv = ieee80211_priv(dev);
3538         struct ieee80211_device* ieee = priv->ieee80211;
3539         struct ieee80211_network *net = &priv->ieee80211->current_network;
3540         //u16 BcnTimeCfg = 0, BcnCW = 6, BcnIFS = 0xf;
3541         u16 rate_config = 0;
3542         u32 regTmp = 0;
3543         u8 rateIndex = 0;
3544         u8      retrylimit = 0x30;
3545         u16 cap = net->capability;
3546
3547         priv->short_preamble = cap & WLAN_CAPABILITY_SHORT_PREAMBLE;
3548
3549 //HW_VAR_BASIC_RATE
3550         //update Basic rate: RR, BRSR
3551         rtl8192_config_rate(dev, &rate_config); //HalSetBrateCfg
3552
3553         priv->basic_rate = rate_config  = rate_config & 0x15f;
3554
3555         // Set RRSR rate table.
3556         write_nic_byte(dev, RRSR, rate_config&0xff);
3557         write_nic_byte(dev, RRSR+1, (rate_config>>8)&0xff);
3558
3559         // Set RTS initial rate
3560         while(rate_config > 0x1)
3561         {
3562                 rate_config = (rate_config>> 1);
3563                 rateIndex++;
3564         }
3565         write_nic_byte(dev, INIRTSMCS_SEL, rateIndex);
3566 //HW_VAR_BASIC_RATE
3567
3568         //set ack preample
3569         regTmp = (priv->nCur40MhzPrimeSC) << 5;
3570         if (priv->short_preamble)
3571                 regTmp |= 0x80;
3572         write_nic_byte(dev, RRSR+2, regTmp);
3573
3574         write_nic_dword(dev,BSSIDR,((u32*)net->bssid)[0]);
3575         write_nic_word(dev,BSSIDR+4,((u16*)net->bssid)[2]);
3576
3577         write_nic_word(dev, BCN_INTERVAL, net->beacon_interval);
3578         //2008.10.24 added by tynli for beacon changed.
3579         PHY_SetBeaconHwReg( dev, net->beacon_interval);
3580
3581         rtl8192_update_cap(dev, cap);
3582
3583         if (ieee->iw_mode == IW_MODE_ADHOC){
3584                 retrylimit = 7;
3585                 //we should enable ibss interrupt here, but disable it temporarily
3586                 if (0){
3587                         priv->irq_mask |= (IMR_BcnInt | IMR_BcnInt | IMR_TBDOK | IMR_TBDER);
3588                         //rtl8192_irq_disable(dev);
3589                         //rtl8192_irq_enable(dev);
3590                 }
3591         }
3592         else{
3593                 if (0){
3594                         priv->irq_mask &= ~(IMR_BcnInt | IMR_BcnInt | IMR_TBDOK | IMR_TBDER);
3595                         //rtl8192_irq_disable(dev);
3596                         //rtl8192_irq_enable(dev);
3597                 }
3598         }
3599
3600         priv->ShortRetryLimit = priv->LongRetryLimit = retrylimit;
3601
3602         write_nic_word(dev,     RETRY_LIMIT,
3603                                 retrylimit << RETRY_LIMIT_SHORT_SHIFT | \
3604                                 retrylimit << RETRY_LIMIT_LONG_SHIFT);
3605 }
3606
3607 void rtl8192SU_update_ratr_table(struct net_device* dev)
3608 {
3609                 struct r8192_priv* priv = ieee80211_priv(dev);
3610         struct ieee80211_device* ieee = priv->ieee80211;
3611         u8* pMcsRate = ieee->dot11HTOperationalRateSet;
3612         //struct ieee80211_network *net = &ieee->current_network;
3613         u32 ratr_value = 0;
3614
3615         u8 rate_index = 0;
3616         int WirelessMode = ieee->mode;
3617         u8 MimoPs = ieee->pHTInfo->PeerMimoPs;
3618
3619         u8 bNMode = 0;
3620
3621         rtl8192_config_rate(dev, (u16*)(&ratr_value));
3622         ratr_value |= (*(u16*)(pMcsRate)) << 12;
3623
3624         //switch (ieee->mode)
3625         switch (WirelessMode)
3626         {
3627                 case IEEE_A:
3628                         ratr_value &= 0x00000FF0;
3629                         break;
3630                 case IEEE_B:
3631                         ratr_value &= 0x0000000D;
3632                         break;
3633                 case IEEE_G:
3634                         ratr_value &= 0x00000FF5;
3635                         break;
3636                 case IEEE_N_24G:
3637                 case IEEE_N_5G:
3638                 {
3639                         bNMode = 1;
3640
3641                         if (MimoPs == 0) //MIMO_PS_STATIC
3642                                         {
3643                                 ratr_value &= 0x0007F005;
3644                         }
3645                         else
3646                         {       // MCS rate only => for 11N mode.
3647                                 u32     ratr_mask;
3648
3649                                 // 1T2R or 1T1R, Spatial Stream 2 should be disabled
3650                                 if (    priv->rf_type == RF_1T2R ||
3651                                         priv->rf_type == RF_1T1R ||
3652                                         (ieee->pHTInfo->IOTAction & HT_IOT_ACT_DISABLE_TX_2SS) )
3653                                                 ratr_mask = 0x000ff005;
3654                                         else
3655                                                 ratr_mask = 0x0f0ff005;
3656
3657                                 if((ieee->pHTInfo->bCurTxBW40MHz) &&
3658                                     !(ieee->pHTInfo->IOTAction & HT_IOT_ACT_DISABLE_TX_40_MHZ))
3659                                         ratr_mask |= 0x00000010; // Set 6MBps
3660
3661                                 // Select rates for rate adaptive mechanism.
3662                                         ratr_value &= ratr_mask;
3663                                         }
3664                         }
3665                         break;
3666                 default:
3667                         if(0)
3668                         {
3669                                 if(priv->rf_type == RF_1T2R)    // 1T2R, Spatial Stream 2 should be disabled
3670                                 {
3671                                 ratr_value &= 0x000ff0f5;
3672                                 }
3673                                 else
3674                                 {
3675                                 ratr_value &= 0x0f0ff0f5;
3676                                 }
3677                         }
3678                         //printk("====>%s(), mode is not correct:%x\n", __FUNCTION__, ieee->mode);
3679                         break;
3680         }
3681
3682         ratr_value &= 0x0FFFFFFF;
3683
3684         // Get MAX MCS available.
3685         if (   (bNMode && ((ieee->pHTInfo->IOTAction & HT_IOT_ACT_DISABLE_SHORT_GI)==0)) &&
3686                 ((ieee->pHTInfo->bCurBW40MHz && ieee->pHTInfo->bCurShortGI40MHz) ||
3687                 (!ieee->pHTInfo->bCurBW40MHz && ieee->pHTInfo->bCurShortGI20MHz)))
3688         {
3689                 u8 shortGI_rate = 0;
3690                 u32 tmp_ratr_value = 0;
3691                 ratr_value |= 0x10000000;//???
3692                 tmp_ratr_value = (ratr_value>>12);
3693                 for(shortGI_rate=15; shortGI_rate>0; shortGI_rate--)
3694                 {
3695                         if((1<<shortGI_rate) & tmp_ratr_value)
3696                                 break;
3697                 }
3698                 shortGI_rate = (shortGI_rate<<12)|(shortGI_rate<<8)|(shortGI_rate<<4)|(shortGI_rate);
3699                 write_nic_byte(dev, SG_RATE, shortGI_rate);
3700                 //printk("==>SG_RATE:%x\n", read_nic_byte(dev, SG_RATE));
3701         }
3702         write_nic_dword(dev, ARFR0+rate_index*4, ratr_value);
3703         printk("=============>ARFR0+rate_index*4:%#x\n", ratr_value);
3704
3705         //2 UFWP
3706         if (ratr_value & 0xfffff000){
3707                 //printk("===>set to N mode\n");
3708                 HalSetFwCmd8192S(dev, FW_CMD_RA_REFRESH_N);
3709         }
3710         else    {
3711                 //printk("===>set to B/G mode\n");
3712                 HalSetFwCmd8192S(dev, FW_CMD_RA_REFRESH_BG);
3713         }
3714 }
3715
3716 void rtl8192SU_link_change(struct net_device *dev)
3717 {
3718         struct r8192_priv *priv = ieee80211_priv(dev);
3719         struct ieee80211_device* ieee = priv->ieee80211;
3720         //unsigned long flags;
3721         u32 reg = 0;
3722
3723         printk("=====>%s 1\n", __func__);
3724         reg = read_nic_dword(dev, RCR);
3725
3726         if (ieee->state == IEEE80211_LINKED)
3727         {
3728
3729                 rtl8192SU_net_update(dev);
3730                 rtl8192SU_update_ratr_table(dev);
3731                 ieee->SetFwCmdHandler(dev, FW_CMD_HIGH_PWR_ENABLE);
3732                 priv->ReceiveConfig = reg |= RCR_CBSSID;
3733
3734         }else{
3735                 priv->ReceiveConfig = reg &= ~RCR_CBSSID;
3736
3737         }
3738
3739         write_nic_dword(dev, RCR, reg);
3740         rtl8192_update_msr(dev);
3741
3742         printk("<=====%s 2\n", __func__);
3743 }
3744 #else
3745 extern void rtl8192_update_ratr_table(struct net_device* dev);
3746 void rtl8192_link_change(struct net_device *dev)
3747 {
3748 //      int i;
3749
3750         struct r8192_priv *priv = ieee80211_priv(dev);
3751         struct ieee80211_device* ieee = priv->ieee80211;
3752         //write_nic_word(dev, BCN_INTR_ITV, net->beacon_interval);
3753         if (ieee->state == IEEE80211_LINKED)
3754         {
3755                 rtl8192_net_update(dev);
3756                 rtl8192_update_ratr_table(dev);
3757 #if 1
3758                 //add this as in pure N mode, wep encryption will use software way, but there is no chance to set this as wep will not set group key in wext. WB.2008.07.08
3759                 if ((KEY_TYPE_WEP40 == ieee->pairwise_key_type) || (KEY_TYPE_WEP104 == ieee->pairwise_key_type))
3760                 EnableHWSecurityConfig8192(dev);
3761 #endif
3762         }
3763         /*update timing params*/
3764 //      RT_TRACE(COMP_CH, "========>%s(), chan:%d\n", __FUNCTION__, priv->chan);
3765 //      rtl8192_set_chan(dev, priv->chan);
3766          if (ieee->iw_mode == IW_MODE_INFRA || ieee->iw_mode == IW_MODE_ADHOC)
3767         {
3768                 u32 reg = 0;
3769                 reg = read_nic_dword(dev, RCR);
3770                 if (priv->ieee80211->state == IEEE80211_LINKED)
3771                         priv->ReceiveConfig = reg |= RCR_CBSSID;
3772                 else
3773                         priv->ReceiveConfig = reg &= ~RCR_CBSSID;
3774                 write_nic_dword(dev, RCR, reg);
3775         }
3776
3777 //      rtl8192_set_rxconf(dev);
3778 }
3779 #endif
3780
3781 static struct ieee80211_qos_parameters def_qos_parameters = {
3782         {3,3,3,3},/* cw_min */
3783         {7,7,7,7},/* cw_max */
3784         {2,2,2,2},/* aifs */
3785         {0,0,0,0},/* flags */
3786         {0,0,0,0} /* tx_op_limit */
3787 };
3788
3789
3790 void rtl8192_update_beacon(struct work_struct * work)
3791 {
3792         struct r8192_priv *priv = container_of(work, struct r8192_priv, update_beacon_wq.work);
3793         struct net_device *dev = priv->ieee80211->dev;
3794         struct ieee80211_device* ieee = priv->ieee80211;
3795         struct ieee80211_network* net = &ieee->current_network;
3796
3797         if (ieee->pHTInfo->bCurrentHTSupport)
3798                 HTUpdateSelfAndPeerSetting(ieee, net);
3799         ieee->pHTInfo->bCurrentRT2RTLongSlotTime = net->bssht.bdRT2RTLongSlotTime;
3800         // Joseph test for turbo mode with AP
3801         ieee->pHTInfo->RT2RT_HT_Mode = net->bssht.RT2RT_HT_Mode;
3802         rtl8192_update_cap(dev, net->capability);
3803 }
3804 /*
3805 * background support to run QoS activate functionality
3806 */
3807 int WDCAPARA_ADD[] = {EDCAPARA_BE,EDCAPARA_BK,EDCAPARA_VI,EDCAPARA_VO};
3808
3809 void rtl8192_qos_activate(struct work_struct * work)
3810 {
3811         struct r8192_priv *priv = container_of(work, struct r8192_priv, qos_activate);
3812         struct net_device *dev = priv->ieee80211->dev;
3813         struct ieee80211_qos_parameters *qos_parameters = &priv->ieee80211->current_network.qos_data.parameters;
3814         u8 mode = priv->ieee80211->current_network.mode;
3815         //u32 size = sizeof(struct ieee80211_qos_parameters);
3816         u8  u1bAIFS;
3817         u32 u4bAcParam;
3818         int i;
3819
3820         if (priv == NULL)
3821                 return;
3822
3823        mutex_lock(&priv->mutex);
3824
3825         if(priv->ieee80211->state != IEEE80211_LINKED)
3826                 goto success;
3827         RT_TRACE(COMP_QOS,"qos active process with associate response received\n");
3828         /* It better set slot time at first */
3829         /* For we just support b/g mode at present, let the slot time at 9/20 selection */
3830         /* update the ac parameter to related registers */
3831         for(i = 0; i <  QOS_QUEUE_NUM; i++) {
3832                 //Mode G/A: slotTimeTimer = 9; Mode B: 20
3833                 u1bAIFS = qos_parameters->aifs[i] * ((mode&(IEEE_G|IEEE_N_24G)) ?9:20) + aSifsTime;
3834                 u4bAcParam = ((((u32)(qos_parameters->tx_op_limit[i]))<< AC_PARAM_TXOP_LIMIT_OFFSET)|
3835                                 (((u32)(qos_parameters->cw_max[i]))<< AC_PARAM_ECW_MAX_OFFSET)|
3836                                 (((u32)(qos_parameters->cw_min[i]))<< AC_PARAM_ECW_MIN_OFFSET)|
3837                                 ((u32)u1bAIFS << AC_PARAM_AIFS_OFFSET));
3838
3839                 write_nic_dword(dev, WDCAPARA_ADD[i], u4bAcParam);
3840                 //write_nic_dword(dev, WDCAPARA_ADD[i], 0x005e4322);
3841         }
3842
3843 success:
3844        mutex_unlock(&priv->mutex);
3845 }
3846
3847 static int rtl8192_qos_handle_probe_response(struct r8192_priv *priv,
3848                 int active_network,
3849                 struct ieee80211_network *network)
3850 {
3851         int ret = 0;
3852         u32 size = sizeof(struct ieee80211_qos_parameters);
3853
3854         if(priv->ieee80211->state !=IEEE80211_LINKED)
3855                 return ret;
3856
3857         if ((priv->ieee80211->iw_mode != IW_MODE_INFRA))
3858                 return ret;
3859
3860         if (network->flags & NETWORK_HAS_QOS_MASK) {
3861                 if (active_network &&
3862                                 (network->flags & NETWORK_HAS_QOS_PARAMETERS))
3863                         network->qos_data.active = network->qos_data.supported;
3864
3865                 if ((network->qos_data.active == 1) && (active_network == 1) &&
3866                                 (network->flags & NETWORK_HAS_QOS_PARAMETERS) &&
3867                                 (network->qos_data.old_param_count !=
3868                                  network->qos_data.param_count)) {
3869                         network->qos_data.old_param_count =
3870                                 network->qos_data.param_count;
3871                         queue_work(priv->priv_wq, &priv->qos_activate);
3872                         RT_TRACE (COMP_QOS, "QoS parameters change call "
3873                                         "qos_activate\n");
3874                 }
3875         } else {
3876                 memcpy(&priv->ieee80211->current_network.qos_data.parameters,\
3877                        &def_qos_parameters, size);
3878
3879                 if ((network->qos_data.active == 1) && (active_network == 1)) {
3880                         queue_work(priv->priv_wq, &priv->qos_activate);
3881                         RT_TRACE(COMP_QOS, "QoS was disabled call qos_activate \n");
3882                 }
3883                 network->qos_data.active = 0;
3884                 network->qos_data.supported = 0;
3885         }
3886
3887         return 0;
3888 }
3889
3890 /* handle manage frame frame beacon and probe response */
3891 static int rtl8192_handle_beacon(struct net_device * dev,
3892                               struct ieee80211_beacon * beacon,
3893                               struct ieee80211_network * network)
3894 {
3895         struct r8192_priv *priv = ieee80211_priv(dev);
3896
3897         rtl8192_qos_handle_probe_response(priv,1,network);
3898         queue_delayed_work(priv->priv_wq, &priv->update_beacon_wq, 0);
3899
3900         return 0;
3901
3902 }
3903
3904 /*
3905 * handling the beaconing responses. if we get different QoS setting
3906 * off the network from the associated setting, adjust the QoS
3907 * setting
3908 */
3909 static int rtl8192_qos_association_resp(struct r8192_priv *priv,
3910                                     struct ieee80211_network *network)
3911 {
3912         int ret = 0;
3913         unsigned long flags;
3914         u32 size = sizeof(struct ieee80211_qos_parameters);
3915         int set_qos_param = 0;
3916
3917         if ((priv == NULL) || (network == NULL))
3918                 return ret;
3919
3920         if(priv->ieee80211->state !=IEEE80211_LINKED)
3921                 return ret;
3922
3923         if ((priv->ieee80211->iw_mode != IW_MODE_INFRA))
3924                 return ret;
3925
3926         spin_lock_irqsave(&priv->ieee80211->lock, flags);
3927         if(network->flags & NETWORK_HAS_QOS_PARAMETERS) {
3928                 memcpy(&priv->ieee80211->current_network.qos_data.parameters,\
3929                          &network->qos_data.parameters,\
3930                         sizeof(struct ieee80211_qos_parameters));
3931                 priv->ieee80211->current_network.qos_data.active = 1;
3932 #if 0
3933                 if((priv->ieee80211->current_network.qos_data.param_count != \
3934                                         network->qos_data.param_count))
3935 #endif
3936                  {
3937                         set_qos_param = 1;
3938                         /* update qos parameter for current network */
3939                         priv->ieee80211->current_network.qos_data.old_param_count = \
3940                                  priv->ieee80211->current_network.qos_data.param_count;
3941                         priv->ieee80211->current_network.qos_data.param_count = \
3942                                  network->qos_data.param_count;
3943                 }
3944         } else {
3945                 memcpy(&priv->ieee80211->current_network.qos_data.parameters,\
3946                        &def_qos_parameters, size);
3947                 priv->ieee80211->current_network.qos_data.active = 0;
3948                 priv->ieee80211->current_network.qos_data.supported = 0;
3949                 set_qos_param = 1;
3950         }
3951
3952         spin_unlock_irqrestore(&priv->ieee80211->lock, flags);
3953
3954         RT_TRACE(COMP_QOS, "%s: network->flags = %d,%d\n",__FUNCTION__,network->flags ,priv->ieee80211->current_network.qos_data.active);
3955         if (set_qos_param == 1)
3956                 queue_work(priv->priv_wq, &priv->qos_activate);
3957
3958         return ret;
3959 }
3960
3961
3962 static int rtl8192_handle_assoc_response(struct net_device *dev,
3963                                      struct ieee80211_assoc_response_frame *resp,
3964                                      struct ieee80211_network *network)
3965 {
3966         struct r8192_priv *priv = ieee80211_priv(dev);
3967         rtl8192_qos_association_resp(priv, network);
3968         return 0;
3969 }
3970
3971
3972 void rtl8192_update_ratr_table(struct net_device* dev)
3973         //      POCTET_STRING   posLegacyRate,
3974         //      u8*                     pMcsRate)
3975         //      PRT_WLAN_STA    pEntry)
3976 {
3977         struct r8192_priv* priv = ieee80211_priv(dev);
3978         struct ieee80211_device* ieee = priv->ieee80211;
3979         u8* pMcsRate = ieee->dot11HTOperationalRateSet;
3980         //struct ieee80211_network *net = &ieee->current_network;
3981         u32 ratr_value = 0;
3982         u8 rate_index = 0;
3983         rtl8192_config_rate(dev, (u16*)(&ratr_value));
3984         ratr_value |= (*(u16*)(pMcsRate)) << 12;
3985 //      switch (net->mode)
3986         switch (ieee->mode)
3987         {
3988                 case IEEE_A:
3989                         ratr_value &= 0x00000FF0;
3990                         break;
3991                 case IEEE_B:
3992                         ratr_value &= 0x0000000F;
3993                         break;
3994                 case IEEE_G:
3995                         ratr_value &= 0x00000FF7;
3996                         break;
3997                 case IEEE_N_24G:
3998                 case IEEE_N_5G:
3999                         if (ieee->pHTInfo->PeerMimoPs == 0) //MIMO_PS_STATIC
4000                                 ratr_value &= 0x0007F007;
4001                         else{
4002                                 if (priv->rf_type == RF_1T2R)
4003                                         ratr_value &= 0x000FF007;
4004                                 else
4005                                         ratr_value &= 0x0F81F007;
4006                         }
4007                         break;
4008                 default:
4009                         break;
4010         }
4011         ratr_value &= 0x0FFFFFFF;
4012         if(ieee->pHTInfo->bCurTxBW40MHz && ieee->pHTInfo->bCurShortGI40MHz){
4013                 ratr_value |= 0x80000000;
4014         }else if(!ieee->pHTInfo->bCurTxBW40MHz && ieee->pHTInfo->bCurShortGI20MHz){
4015                 ratr_value |= 0x80000000;
4016         }
4017         write_nic_dword(dev, RATR0+rate_index*4, ratr_value);
4018         write_nic_byte(dev, UFWP, 1);
4019 }
4020
4021 static u8 ccmp_ie[4] = {0x00,0x50,0xf2,0x04};
4022 static u8 ccmp_rsn_ie[4] = {0x00, 0x0f, 0xac, 0x04};
4023 bool GetNmodeSupportBySecCfg8192(struct net_device*dev)
4024 {
4025 #if 1
4026         struct r8192_priv* priv = ieee80211_priv(dev);
4027         struct ieee80211_device* ieee = priv->ieee80211;
4028         struct ieee80211_network * network = &ieee->current_network;
4029         int wpa_ie_len= ieee->wpa_ie_len;
4030         struct ieee80211_crypt_data* crypt;
4031         int encrypt;
4032 #if (defined (RTL8192SU_FPGA_2MAC_VERIFICATION)||defined (RTL8192SU_ASIC_VERIFICATION))
4033         return TRUE;
4034 #endif
4035
4036         crypt = ieee->crypt[ieee->tx_keyidx];
4037         //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
4038         encrypt = (network->capability & WLAN_CAPABILITY_PRIVACY) || (ieee->host_encrypt && crypt && crypt->ops && (0 == strcmp(crypt->ops->name,"WEP")));
4039
4040         /* simply judge  */
4041         if(encrypt && (wpa_ie_len == 0)) {
4042                 /* wep encryption, no N mode setting */
4043                 return false;
4044 //      } else if((wpa_ie_len != 0)&&(memcmp(&(ieee->wpa_ie[14]),ccmp_ie,4))) {
4045         } else if((wpa_ie_len != 0)) {
4046                 /* parse pairwise key type */
4047                 //if((pairwisekey = WEP40)||(pairwisekey = WEP104)||(pairwisekey = TKIP))
4048                 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))))
4049                         return true;
4050                 else
4051                         return false;
4052         } else {
4053                 return true;
4054         }
4055
4056 #if 0
4057         //In here we discuss with SD4 David. He think we still can send TKIP in broadcast group key in MCS rate.
4058         //We can't force in G mode if Pairwie key is AES and group key is TKIP
4059         if((pSecInfo->GroupEncAlgorithm == WEP104_Encryption) || (pSecInfo->GroupEncAlgorithm == WEP40_Encryption)  ||
4060            (pSecInfo->PairwiseEncAlgorithm == WEP104_Encryption) ||
4061            (pSecInfo->PairwiseEncAlgorithm == WEP40_Encryption) || (pSecInfo->PairwiseEncAlgorithm == TKIP_Encryption))
4062         {
4063                 return  false;
4064         }
4065         else
4066                 return true;
4067 #endif
4068         return true;
4069 #endif
4070 }
4071
4072 bool GetHalfNmodeSupportByAPs819xUsb(struct net_device* dev)
4073 {
4074         bool                    Reval;
4075         struct r8192_priv* priv = ieee80211_priv(dev);
4076         struct ieee80211_device* ieee = priv->ieee80211;
4077
4078 //      Added by Roger, 2008.08.29.
4079 #ifdef RTL8192SU
4080         return false;
4081 #endif
4082
4083         if(ieee->bHalfWirelessN24GMode == true)
4084                 Reval = true;
4085         else
4086                 Reval =  false;
4087
4088         return Reval;
4089 }
4090
4091 void rtl8192_refresh_supportrate(struct r8192_priv* priv)
4092 {
4093         struct ieee80211_device* ieee = priv->ieee80211;
4094         //we donot consider set support rate for ABG mode, only HT MCS rate is set here.
4095         if (ieee->mode == WIRELESS_MODE_N_24G || ieee->mode == WIRELESS_MODE_N_5G)
4096         {
4097                 memcpy(ieee->Regdot11HTOperationalRateSet, ieee->RegHTSuppRateSet, 16);
4098                 //RT_DEBUG_DATA(COMP_INIT, ieee->RegHTSuppRateSet, 16);
4099                 //RT_DEBUG_DATA(COMP_INIT, ieee->Regdot11HTOperationalRateSet, 16);
4100         }
4101         else
4102                 memset(ieee->Regdot11HTOperationalRateSet, 0, 16);
4103         return;
4104 }
4105
4106 u8 rtl8192_getSupportedWireleeMode(struct net_device*dev)
4107 {
4108         struct r8192_priv *priv = ieee80211_priv(dev);
4109         u8 ret = 0;
4110         switch(priv->rf_chip)
4111         {
4112                 case RF_8225:
4113                 case RF_8256:
4114                 case RF_PSEUDO_11N:
4115                 case RF_6052:
4116                         ret = (WIRELESS_MODE_N_24G|WIRELESS_MODE_G|WIRELESS_MODE_B);
4117                         break;
4118                 case RF_8258:
4119                         ret = (WIRELESS_MODE_A|WIRELESS_MODE_N_5G);
4120                         break;
4121                 default:
4122                         ret = WIRELESS_MODE_B;
4123                         break;
4124         }
4125         return ret;
4126 }
4127 void rtl8192_SetWirelessMode(struct net_device* dev, u8 wireless_mode)
4128 {
4129         struct r8192_priv *priv = ieee80211_priv(dev);
4130         u8 bSupportMode = rtl8192_getSupportedWireleeMode(dev);
4131
4132 #if 1
4133         if ((wireless_mode == WIRELESS_MODE_AUTO) || ((wireless_mode&bSupportMode)==0))
4134         {
4135                 if(bSupportMode & WIRELESS_MODE_N_24G)
4136                 {
4137                         wireless_mode = WIRELESS_MODE_N_24G;
4138                 }
4139                 else if(bSupportMode & WIRELESS_MODE_N_5G)
4140                 {
4141                         wireless_mode = WIRELESS_MODE_N_5G;
4142                 }
4143                 else if((bSupportMode & WIRELESS_MODE_A))
4144                 {
4145                         wireless_mode = WIRELESS_MODE_A;
4146                 }
4147                 else if((bSupportMode & WIRELESS_MODE_G))
4148                 {
4149                         wireless_mode = WIRELESS_MODE_G;
4150                 }
4151                 else if((bSupportMode & WIRELESS_MODE_B))
4152                 {
4153                         wireless_mode = WIRELESS_MODE_B;
4154                 }
4155                 else{
4156                         RT_TRACE(COMP_ERR, "%s(), No valid wireless mode supported, SupportedWirelessMode(%x)!!!\n", __FUNCTION__,bSupportMode);
4157                         wireless_mode = WIRELESS_MODE_B;
4158                 }
4159         }
4160 #ifdef TO_DO_LIST //// TODO: this function doesn't work well at this time, we shoud wait for FPGA
4161         ActUpdateChannelAccessSetting( pAdapter, pHalData->CurrentWirelessMode, &pAdapter->MgntInfo.Info8185.ChannelAccessSetting );
4162 #endif
4163 #ifdef RTL8192SU
4164         //LZM 090306 usb crash here, mark it temp
4165         //write_nic_word(dev, SIFS_OFDM, 0x0e0e);
4166 #endif
4167         priv->ieee80211->mode = wireless_mode;
4168
4169         if ((wireless_mode == WIRELESS_MODE_N_24G) ||  (wireless_mode == WIRELESS_MODE_N_5G))
4170                 priv->ieee80211->pHTInfo->bEnableHT = 1;
4171         else
4172                 priv->ieee80211->pHTInfo->bEnableHT = 0;
4173         RT_TRACE(COMP_INIT, "Current Wireless Mode is %x\n", wireless_mode);
4174         rtl8192_refresh_supportrate(priv);
4175 #endif
4176
4177 }
4178
4179
4180 short rtl8192_is_tx_queue_empty(struct net_device *dev)
4181 {
4182         int i=0;
4183         struct r8192_priv *priv = ieee80211_priv(dev);
4184         //struct ieee80211_device* ieee = priv->ieee80211;
4185         for (i=0; i<=MGNT_QUEUE; i++)
4186         {
4187                 if ((i== TXCMD_QUEUE) || (i == HCCA_QUEUE) )
4188                         continue;
4189                 if (atomic_read(&priv->tx_pending[i]))
4190                 {
4191                         printk("===>tx queue is not empty:%d, %d\n", i, atomic_read(&priv->tx_pending[i]));
4192                         return 0;
4193                 }
4194         }
4195         return 1;
4196 }
4197 #if 0
4198 void rtl8192_rq_tx_ack(struct net_device *dev)
4199 {
4200         struct r8192_priv *priv = ieee80211_priv(dev);
4201         priv->ieee80211->ack_tx_to_ieee = 1;
4202 }
4203 #endif
4204 void rtl8192_hw_sleep_down(struct net_device *dev)
4205 {
4206         RT_TRACE(COMP_POWER, "%s()============>come to sleep down\n", __FUNCTION__);
4207 #ifdef TODO
4208 //      MgntActSet_RF_State(dev, eRfSleep, RF_CHANGE_BY_PS);
4209 #endif
4210 }
4211
4212 void rtl8192_hw_sleep_wq (struct work_struct *work)
4213 {
4214 //      struct r8180_priv *priv = container_of(work, struct r8180_priv, watch_dog_wq);
4215 //      struct ieee80211_device * ieee = (struct ieee80211_device*)
4216 //                                             container_of(work, struct ieee80211_device, watch_dog_wq);
4217         struct delayed_work *dwork = container_of(work,struct delayed_work,work);
4218         struct ieee80211_device *ieee = container_of(dwork,struct ieee80211_device,hw_sleep_wq);
4219         struct net_device *dev = ieee->dev;
4220
4221         //printk("=========>%s()\n", __FUNCTION__);
4222         rtl8192_hw_sleep_down(dev);
4223 }
4224 //      printk("dev is %d\n",dev);
4225 //      printk("&*&(^*(&(&=========>%s()\n", __FUNCTION__);
4226 void rtl8192_hw_wakeup(struct net_device* dev)
4227 {
4228 //      u32 flags = 0;
4229
4230 //      spin_lock_irqsave(&priv->ps_lock,flags);
4231         RT_TRACE(COMP_POWER, "%s()============>come to wake up\n", __FUNCTION__);
4232 #ifdef TODO
4233 //      MgntActSet_RF_State(dev, eRfSleep, RF_CHANGE_BY_PS);
4234 #endif
4235         //FIXME: will we send package stored while nic is sleep?
4236 //      spin_unlock_irqrestore(&priv->ps_lock,flags);
4237 }
4238
4239 void rtl8192_hw_wakeup_wq (struct work_struct *work)
4240 {
4241 //      struct r8180_priv *priv = container_of(work, struct r8180_priv, watch_dog_wq);
4242 //      struct ieee80211_device * ieee = (struct ieee80211_device*)
4243 //                                             container_of(work, struct ieee80211_device, watch_dog_wq);
4244         struct delayed_work *dwork = container_of(work,struct delayed_work,work);
4245         struct ieee80211_device *ieee = container_of(dwork,struct ieee80211_device,hw_wakeup_wq);
4246         struct net_device *dev = ieee->dev;
4247
4248         rtl8192_hw_wakeup(dev);
4249 }
4250
4251 #define MIN_SLEEP_TIME 50
4252 #define MAX_SLEEP_TIME 10000
4253 void rtl8192_hw_to_sleep(struct net_device *dev, u32 th, u32 tl)
4254 {
4255
4256         struct r8192_priv *priv = ieee80211_priv(dev);
4257
4258         u32 rb = jiffies;
4259         unsigned long flags;
4260
4261         spin_lock_irqsave(&priv->ps_lock,flags);
4262
4263         /* Writing HW register with 0 equals to disable
4264          * the timer, that is not really what we want
4265          */
4266         tl -= MSECS(4+16+7);
4267
4268         //if(tl == 0) tl = 1;
4269
4270         /* FIXME HACK FIXME HACK */
4271 //      force_pci_posting(dev);
4272         //mdelay(1);
4273
4274 //      rb = read_nic_dword(dev, TSFTR);
4275
4276         /* If the interval in witch we are requested to sleep is too
4277          * short then give up and remain awake
4278          */
4279         if(((tl>=rb)&& (tl-rb) <= MSECS(MIN_SLEEP_TIME))
4280                 ||((rb>tl)&& (rb-tl) < MSECS(MIN_SLEEP_TIME))) {
4281                 spin_unlock_irqrestore(&priv->ps_lock,flags);
4282                 printk("too short to sleep\n");
4283                 return;
4284         }
4285
4286 //      write_nic_dword(dev, TimerInt, tl);
4287 //      rb = read_nic_dword(dev, TSFTR);
4288         {
4289                 u32 tmp = (tl>rb)?(tl-rb):(rb-tl);
4290         //      if (tl<rb)
4291
4292                 queue_delayed_work(priv->ieee80211->wq, &priv->ieee80211->hw_wakeup_wq, tmp); //as tl may be less than rb
4293         }
4294         /* if we suspect the TimerInt is gone beyond tl
4295          * while setting it, then give up
4296          */
4297 #if 1
4298         if(((tl > rb) && ((tl-rb) > MSECS(MAX_SLEEP_TIME)))||
4299                 ((tl < rb) && ((rb-tl) > MSECS(MAX_SLEEP_TIME)))) {
4300                 printk("========>too long to sleep:%x, %x, %lx\n", tl, rb,  MSECS(MAX_SLEEP_TIME));
4301                 spin_unlock_irqrestore(&priv->ps_lock,flags);
4302                 return;
4303         }
4304 #endif
4305 //      if(priv->rf_sleep)
4306 //              priv->rf_sleep(dev);
4307
4308         //printk("<=========%s()\n", __FUNCTION__);
4309         queue_delayed_work(priv->ieee80211->wq, (void *)&priv->ieee80211->hw_sleep_wq,0);
4310
4311         spin_unlock_irqrestore(&priv->ps_lock,flags);
4312 }
4313 //init priv variables here. only non_zero value should be initialized here.
4314 static void rtl8192_init_priv_variable(struct net_device* dev)
4315 {
4316         struct r8192_priv *priv = ieee80211_priv(dev);
4317         u8 i;
4318         priv->card_8192 = NIC_8192U;
4319         priv->chan = 1; //set to channel 1
4320         priv->ieee80211->mode = WIRELESS_MODE_AUTO; //SET AUTO
4321         priv->ieee80211->iw_mode = IW_MODE_INFRA;
4322         priv->ieee80211->ieee_up=0;
4323         priv->retry_rts = DEFAULT_RETRY_RTS;
4324         priv->retry_data = DEFAULT_RETRY_DATA;
4325         priv->ieee80211->rts = DEFAULT_RTS_THRESHOLD;
4326         priv->ieee80211->rate = 110; //11 mbps
4327         priv->ieee80211->short_slot = 1;
4328         priv->promisc = (dev->flags & IFF_PROMISC) ? 1:0;
4329         priv->CckPwEnl = 6;
4330         //for silent reset
4331         priv->IrpPendingCount = 1;
4332         priv->ResetProgress = RESET_TYPE_NORESET;
4333         priv->bForcedSilentReset = 0;
4334         priv->bDisableNormalResetCheck = false;
4335         priv->force_reset = false;
4336
4337         priv->ieee80211->FwRWRF = 0;    //we don't use FW read/write RF until stable firmware is available.
4338         priv->ieee80211->current_network.beacon_interval = DEFAULT_BEACONINTERVAL;
4339         priv->ieee80211->iw_mode = IW_MODE_INFRA;
4340         priv->ieee80211->softmac_features  = IEEE_SOFTMAC_SCAN |
4341                 IEEE_SOFTMAC_ASSOCIATE | IEEE_SOFTMAC_PROBERQ |
4342                 IEEE_SOFTMAC_PROBERS | IEEE_SOFTMAC_TX_QUEUE |
4343                 IEEE_SOFTMAC_BEACONS;//added by amy 080604 //|  //IEEE_SOFTMAC_SINGLE_QUEUE;
4344
4345         priv->ieee80211->active_scan = 1;
4346         priv->ieee80211->modulation = IEEE80211_CCK_MODULATION | IEEE80211_OFDM_MODULATION;
4347         priv->ieee80211->host_encrypt = 1;
4348         priv->ieee80211->host_decrypt = 1;
4349         priv->ieee80211->start_send_beacons = NULL;//rtl819xusb_beacon_tx;//-by amy 080604
4350         priv->ieee80211->stop_send_beacons = NULL;//rtl8192_beacon_stop;//-by amy 080604
4351         priv->ieee80211->softmac_hard_start_xmit = rtl8192_hard_start_xmit;
4352         priv->ieee80211->set_chan = rtl8192_set_chan;
4353         priv->ieee80211->link_change = priv->ops->rtl819x_link_change;
4354         priv->ieee80211->softmac_data_hard_start_xmit = rtl8192_hard_data_xmit;
4355         priv->ieee80211->data_hard_stop = rtl8192_data_hard_stop;
4356         priv->ieee80211->data_hard_resume = rtl8192_data_hard_resume;
4357         priv->ieee80211->init_wmmparam_flag = 0;
4358         priv->ieee80211->fts = DEFAULT_FRAG_THRESHOLD;
4359         priv->ieee80211->check_nic_enough_desc = check_nic_enough_desc;
4360         priv->ieee80211->tx_headroom = TX_PACKET_SHIFT_BYTES;
4361         priv->ieee80211->qos_support = 1;
4362
4363         //added by WB
4364 //      priv->ieee80211->SwChnlByTimerHandler = rtl8192_phy_SwChnl;
4365         priv->ieee80211->SetBWModeHandler = rtl8192_SetBWMode;
4366         priv->ieee80211->handle_assoc_response = rtl8192_handle_assoc_response;
4367         priv->ieee80211->handle_beacon = rtl8192_handle_beacon;
4368         //for LPS
4369         priv->ieee80211->sta_wake_up = rtl8192_hw_wakeup;
4370 //      priv->ieee80211->ps_request_tx_ack = rtl8192_rq_tx_ack;
4371         priv->ieee80211->enter_sleep_state = rtl8192_hw_to_sleep;
4372         priv->ieee80211->ps_is_queue_empty = rtl8192_is_tx_queue_empty;
4373         //added by david
4374         priv->ieee80211->GetNmodeSupportBySecCfg = GetNmodeSupportBySecCfg8192;
4375         priv->ieee80211->GetHalfNmodeSupportByAPsHandler = GetHalfNmodeSupportByAPs819xUsb;
4376         priv->ieee80211->SetWirelessMode = rtl8192_SetWirelessMode;
4377         //added by amy
4378         priv->ieee80211->InitialGainHandler = priv->ops->rtl819x_initial_gain;
4379         priv->card_type = USB;
4380
4381 #ifdef RTL8192SU
4382 //1 RTL8192SU/
4383         priv->ieee80211->current_network.beacon_interval = DEFAULT_BEACONINTERVAL;
4384         priv->ieee80211->SetFwCmdHandler = HalSetFwCmd8192S;
4385         priv->bRFSiOrPi = 0;//o=si,1=pi;
4386         //lzm add
4387         priv->bInHctTest = false;
4388
4389         priv->MidHighPwrTHR_L1 = 0x3B;
4390         priv->MidHighPwrTHR_L2 = 0x40;
4391
4392         if(priv->bInHctTest)
4393         {
4394                 priv->ShortRetryLimit = HAL_RETRY_LIMIT_AP_ADHOC;
4395                 priv->LongRetryLimit = HAL_RETRY_LIMIT_AP_ADHOC;
4396         }
4397         else
4398         {
4399                 priv->ShortRetryLimit = HAL_RETRY_LIMIT_INFRA;
4400                 priv->LongRetryLimit = HAL_RETRY_LIMIT_INFRA;
4401         }
4402
4403         priv->SetFwCmdInProgress = false; //is set FW CMD in Progress? 92S only
4404         priv->CurrentFwCmdIO = 0;
4405
4406         priv->MinSpaceCfg = 0;
4407
4408         priv->EarlyRxThreshold = 7;
4409         priv->enable_gpio0 = 0;
4410         priv->TransmitConfig    =
4411                                 ((u32)TCR_MXDMA_2048<<TCR_MXDMA_OFFSET) |       // Max DMA Burst Size per Tx DMA Burst, 7: reservied.
4412                                 (priv->ShortRetryLimit<<TCR_SRL_OFFSET) |       // Short retry limit
4413                                 (priv->LongRetryLimit<<TCR_LRL_OFFSET) |        // Long retry limit
4414                                 (false ? TCR_SAT : 0);  // FALSE: HW provies PLCP length and LENGEXT, TURE: SW proiveds them
4415         if(priv->bInHctTest)
4416                 priv->ReceiveConfig     =       //priv->CSMethod |
4417                                                                 RCR_AMF | RCR_ADF |     //RCR_AAP |     //accept management/data
4418                                                                         RCR_ACF |RCR_APPFCS|                                            //accept control frame for SW AP needs PS-poll, 2005.07.07, by rcnjko.
4419                                                                 RCR_AB | RCR_AM | RCR_APM |             //accept BC/MC/UC
4420                                                                 RCR_AICV | RCR_ACRC32 |                 //accept ICV/CRC error packet
4421                                                                 RCR_APP_PHYST_STAFF | RCR_APP_PHYST_RXFF |      // Accept PHY status
4422                                                                 ((u32)7<<RCR_MXDMA_OFFSET) | // Max DMA Burst Size per Rx DMA Burst, 7: unlimited.
4423                                                                 (priv->EarlyRxThreshold<<RCR_FIFO_OFFSET) | // Rx FIFO Threshold, 7: No Rx threshold.
4424                                                                 (priv->EarlyRxThreshold == 7 ? RCR_OnlyErlPkt:0);
4425         else
4426                 priv->ReceiveConfig     =       //priv->CSMethod |
4427                                                                         RCR_AMF | RCR_ADF | RCR_AB |
4428                                                                         RCR_AM | RCR_APM |RCR_AAP |RCR_ADD3|RCR_APP_ICV|
4429                                                                 RCR_APP_PHYST_STAFF | RCR_APP_PHYST_RXFF |      // Accept PHY status
4430                                                                         RCR_APP_MIC | RCR_APPFCS;
4431
4432         // <Roger_EXP> 2008.06.16.
4433         priv->IntrMask          =       (u16)(IMR_ROK | IMR_VODOK | IMR_VIDOK | IMR_BEDOK | IMR_BKDOK |         \
4434                                                                 IMR_HCCADOK | IMR_MGNTDOK | IMR_COMDOK | IMR_HIGHDOK |                                  \
4435                                                                 IMR_BDOK | IMR_RXCMDOK | /*IMR_TIMEOUT0 |*/ IMR_RDU | IMR_RXFOVW        |                       \
4436                                                                 IMR_TXFOVW | IMR_BcnInt | IMR_TBDOK | IMR_TBDER);
4437
4438 //1 End
4439
4440 #else
4441
4442 #ifdef TO_DO_LIST
4443         if(Adapter->bInHctTest)
4444         {
4445                 pHalData->ShortRetryLimit = 7;
4446                 pHalData->LongRetryLimit = 7;
4447         }
4448 #endif
4449         {
4450                 priv->ShortRetryLimit = 0x30;
4451                 priv->LongRetryLimit = 0x30;
4452         }
4453         priv->EarlyRxThreshold = 7;
4454         priv->enable_gpio0 = 0;
4455         priv->TransmitConfig =
4456         //      TCR_DurProcMode |       //for RTL8185B, duration setting by HW
4457         //?     TCR_DISReqQsize |
4458                 (TCR_MXDMA_2048<<TCR_MXDMA_OFFSET)|  // Max DMA Burst Size per Tx DMA Burst, 7: reservied.
4459                 (priv->ShortRetryLimit<<TCR_SRL_OFFSET)|        // Short retry limit
4460                 (priv->LongRetryLimit<<TCR_LRL_OFFSET) |        // Long retry limit
4461                 (false ? TCR_SAT: 0);   // FALSE: HW provies PLCP length and LENGEXT, TURE: SW proiveds them
4462 #ifdef TO_DO_LIST
4463         if(Adapter->bInHctTest)
4464                 pHalData->ReceiveConfig =       pHalData->CSMethod |
4465                                                 RCR_AMF | RCR_ADF |     //RCR_AAP |     //accept management/data
4466                                                 //guangan200710
4467                                                 RCR_ACF |       //accept control frame for SW AP needs PS-poll, 2005.07.07, by rcnjko.
4468                                                 RCR_AB | RCR_AM | RCR_APM |             //accept BC/MC/UC
4469                                                 RCR_AICV | RCR_ACRC32 |                 //accept ICV/CRC error packet
4470                                                 ((u32)7<<RCR_MXDMA_OFFSET) | // Max DMA Burst Size per Rx DMA Burst, 7: unlimited.
4471                                                 (pHalData->EarlyRxThreshold<<RCR_FIFO_OFFSET) | // Rx FIFO Threshold, 7: No Rx threshold.
4472                                                 (pHalData->EarlyRxThreshold == 7 ? RCR_OnlyErlPkt:0);
4473         else
4474
4475 #endif
4476         priv->ReceiveConfig     =
4477                 RCR_AMF | RCR_ADF |             //accept management/data
4478                 RCR_ACF |                       //accept control frame for SW AP needs PS-poll, 2005.07.07, by rcnjko.
4479                 RCR_AB | RCR_AM | RCR_APM |     //accept BC/MC/UC
4480                 //RCR_AICV | RCR_ACRC32 |       //accept ICV/CRC error packet
4481                 ((u32)7<<RCR_MXDMA_OFFSET)| // Max DMA Burst Size per Rx DMA Burst, 7: unlimited.
4482                 (priv->EarlyRxThreshold<<RX_FIFO_THRESHOLD_SHIFT) | // Rx FIFO Threshold, 7: No Rx threshold.
4483                 (priv->EarlyRxThreshold == 7 ? RCR_ONLYERLPKT:0);
4484 #endif
4485
4486         priv->AcmControl = 0;
4487         priv->pFirmware = (rt_firmware*)vmalloc(sizeof(rt_firmware));
4488         if (priv->pFirmware)
4489         memset(priv->pFirmware, 0, sizeof(rt_firmware));
4490
4491         /* rx related queue */
4492         skb_queue_head_init(&priv->rx_queue);
4493         skb_queue_head_init(&priv->skb_queue);
4494
4495         /* Tx related queue */
4496         for(i = 0; i < MAX_QUEUE_SIZE; i++) {
4497                 skb_queue_head_init(&priv->ieee80211->skb_waitQ [i]);
4498         }
4499         for(i = 0; i < MAX_QUEUE_SIZE; i++) {
4500                 skb_queue_head_init(&priv->ieee80211->skb_aggQ [i]);
4501         }
4502         for(i = 0; i < MAX_QUEUE_SIZE; i++) {
4503                 skb_queue_head_init(&priv->ieee80211->skb_drv_aggQ [i]);
4504         }
4505         priv->rf_set_chan = rtl8192_phy_SwChnl;
4506 }
4507
4508 //init lock here
4509 static void rtl8192_init_priv_lock(struct r8192_priv* priv)
4510 {
4511         spin_lock_init(&priv->tx_lock);
4512         spin_lock_init(&priv->irq_lock);//added by thomas
4513         //spin_lock_init(&priv->rf_lock);//use rf_sem, or will crash in some OS.
4514         sema_init(&priv->wx_sem,1);
4515         sema_init(&priv->rf_sem,1);
4516         spin_lock_init(&priv->ps_lock);
4517         mutex_init(&priv->mutex);
4518 }
4519
4520 extern  void    rtl819x_watchdog_wqcallback(struct work_struct *work);
4521
4522 void rtl8192_irq_rx_tasklet(struct r8192_priv *priv);
4523 //init tasklet and wait_queue here. only 2.6 above kernel is considered
4524 #define DRV_NAME "wlan0"
4525 static void rtl8192_init_priv_task(struct net_device* dev)
4526 {
4527         struct r8192_priv *priv = ieee80211_priv(dev);
4528
4529 #ifdef PF_SYNCTHREAD
4530         priv->priv_wq = create_workqueue(DRV_NAME,0);
4531 #else
4532         priv->priv_wq = create_workqueue(DRV_NAME);
4533 #endif
4534
4535         INIT_WORK(&priv->reset_wq, rtl8192_restart);
4536
4537         //INIT_DELAYED_WORK(&priv->watch_dog_wq, hal_dm_watchdog);
4538         INIT_DELAYED_WORK(&priv->watch_dog_wq, rtl819x_watchdog_wqcallback);
4539         INIT_DELAYED_WORK(&priv->txpower_tracking_wq,  dm_txpower_trackingcallback);
4540 //      INIT_DELAYED_WORK(&priv->gpio_change_rf_wq,  dm_gpio_change_rf_callback);
4541         INIT_DELAYED_WORK(&priv->rfpath_check_wq,  dm_rf_pathcheck_workitemcallback);
4542         INIT_DELAYED_WORK(&priv->update_beacon_wq, rtl8192_update_beacon);
4543         INIT_DELAYED_WORK(&priv->initialgain_operate_wq, InitialGainOperateWorkItemCallBack);
4544         //INIT_WORK(&priv->SwChnlWorkItem,  rtl8192_SwChnl_WorkItem);
4545         //INIT_WORK(&priv->SetBWModeWorkItem,  rtl8192_SetBWModeWorkItem);
4546         INIT_WORK(&priv->qos_activate, rtl8192_qos_activate);
4547         INIT_DELAYED_WORK(&priv->ieee80211->hw_wakeup_wq,(void*) rtl8192_hw_wakeup_wq);
4548         INIT_DELAYED_WORK(&priv->ieee80211->hw_sleep_wq,(void*) rtl8192_hw_sleep_wq);
4549
4550         tasklet_init(&priv->irq_rx_tasklet,
4551              (void(*)(unsigned long))rtl8192_irq_rx_tasklet,
4552              (unsigned long)priv);
4553 }
4554
4555 static void rtl8192_get_eeprom_size(struct net_device* dev)
4556 {
4557         u16 curCR = 0;
4558         struct r8192_priv *priv = ieee80211_priv(dev);
4559         RT_TRACE(COMP_EPROM, "===========>%s()\n", __FUNCTION__);
4560         curCR = read_nic_word_E(dev,EPROM_CMD);
4561         RT_TRACE(COMP_EPROM, "read from Reg EPROM_CMD(%x):%x\n", EPROM_CMD, curCR);
4562         //whether need I consider BIT5?
4563         priv->epromtype = (curCR & Cmd9346CR_9356SEL) ? EPROM_93c56 : EPROM_93c46;
4564         RT_TRACE(COMP_EPROM, "<===========%s(), epromtype:%d\n", __FUNCTION__, priv->epromtype);
4565 }
4566
4567 //used to swap endian. as ntohl & htonl are not neccessary to swap endian, so use this instead.
4568 static inline u16 endian_swap(u16* data)
4569 {
4570         u16 tmp = *data;
4571         *data = (tmp >> 8) | (tmp << 8);
4572         return *data;
4573 }
4574
4575 #ifdef RTL8192SU
4576 u8 rtl8192SU_UsbOptionToEndPointNumber(u8 UsbOption)
4577 {
4578         u8      nEndPoint = 0;
4579         switch(UsbOption)
4580         {
4581                 case 0:
4582                         nEndPoint = 6;
4583                         break;
4584                 case 1:
4585                         nEndPoint = 11;
4586                         break;
4587                 case 2:
4588                         nEndPoint = 4;
4589                         break;
4590                 default:
4591                         RT_TRACE(COMP_INIT, "UsbOptionToEndPointNumber(): Invalid UsbOption(%#x)\n", UsbOption);
4592                         break;
4593         }
4594         return nEndPoint;
4595 }
4596
4597 u8 rtl8192SU_BoardTypeToRFtype(struct net_device* dev,  u8 Boardtype)
4598 {
4599         u8      RFtype = RF_1T2R;
4600
4601         switch(Boardtype)
4602         {
4603                 case 0:
4604                         RFtype = RF_1T1R;
4605                         break;
4606                 case 1:
4607                         RFtype = RF_1T2R;
4608                         break;
4609                 case 2:
4610                         RFtype = RF_2T2R;
4611                         break;
4612                 case 3:
4613                         RFtype = RF_2T2R_GREEN;
4614                         break;
4615                 default:
4616                         break;
4617         }
4618
4619         return RFtype;
4620 }
4621
4622 //
4623 //      Description:
4624 //              Config HW adapter information into initial value.
4625 //
4626 //      Assumption:
4627 //              1. After Auto load fail(i.e, check CR9346 fail)
4628 //
4629 //      Created by Roger, 2008.10.21.
4630 //
4631 void
4632 rtl8192SU_ConfigAdapterInfo8192SForAutoLoadFail(struct net_device* dev)
4633 {
4634         struct r8192_priv       *priv = ieee80211_priv(dev);
4635         //u16                   i,usValue;
4636         //u8 sMacAddr[6] = {0x00, 0xE0, 0x4C, 0x81, 0x92, 0x00};
4637         u8              rf_path, index; // For EEPROM/EFUSE After V0.6_1117
4638         int     i;
4639
4640         RT_TRACE(COMP_INIT, "====> ConfigAdapterInfo8192SForAutoLoadFail\n");
4641
4642         write_nic_byte(dev, SYS_ISO_CTRL+1, 0xE8); // Isolation signals from Loader
4643         //PlatformStallExecution(10000);
4644         mdelay(10);
4645         write_nic_byte(dev, PMC_FSM, 0x02); // Enable Loader Data Keep
4646
4647         //RT_ASSERT(priv->AutoloadFailFlag==TRUE, ("ReadAdapterInfo8192SEEPROM(): AutoloadFailFlag !=TRUE\n"));
4648
4649         // Initialize IC Version && Channel Plan
4650         priv->eeprom_vid = 0;
4651         priv->eeprom_pid = 0;
4652         priv->card_8192_version = 0;
4653         priv->eeprom_ChannelPlan = 0;
4654         priv->eeprom_CustomerID = 0;
4655         priv->eeprom_SubCustomerID = 0;
4656         priv->bIgnoreDiffRateTxPowerOffset = false;
4657
4658         RT_TRACE(COMP_INIT, "EEPROM VID = 0x%4x\n", priv->eeprom_vid);
4659         RT_TRACE(COMP_INIT, "EEPROM PID = 0x%4x\n", priv->eeprom_pid);
4660         RT_TRACE(COMP_INIT, "EEPROM Customer ID: 0x%2x\n", priv->eeprom_CustomerID);
4661         RT_TRACE(COMP_INIT, "EEPROM SubCustomer ID: 0x%2x\n", priv->eeprom_SubCustomerID);
4662         RT_TRACE(COMP_INIT, "EEPROM ChannelPlan = 0x%4x\n", priv->eeprom_ChannelPlan);
4663         RT_TRACE(COMP_INIT, "IgnoreDiffRateTxPowerOffset = %d\n", priv->bIgnoreDiffRateTxPowerOffset);
4664
4665
4666
4667         priv->EEPROMUsbOption = EEPROM_USB_Default_OPTIONAL_FUNC;
4668         RT_TRACE(COMP_INIT, "USB Option = %#x\n", priv->EEPROMUsbOption);
4669
4670         for(i=0; i<5; i++)
4671                 priv->EEPROMUsbPhyParam[i] = EEPROM_USB_Default_PHY_PARAM;
4672
4673         //RT_PRINT_DATA(COMP_INIT|COMP_EFUSE, DBG_LOUD, ("EFUSE USB PHY Param: \n"), priv->EEPROMUsbPhyParam, 5);
4674
4675         {
4676         //<Roger_Notes> In this case, we random assigh MAC address here. 2008.10.15.
4677                 static u8 sMacAddr[6] = {0x00, 0xE0, 0x4C, 0x81, 0x92, 0x00};
4678                 u8      i;
4679
4680                 //sMacAddr[5] = (u8)GetRandomNumber(1, 254);
4681
4682                 for(i = 0; i < 6; i++)
4683                         dev->dev_addr[i] = sMacAddr[i];
4684         }
4685         //NicIFSetMacAddress(Adapter, Adapter->PermanentAddress);
4686         write_nic_dword(dev, IDR0, ((u32*)dev->dev_addr)[0]);
4687         write_nic_word(dev, IDR4, ((u16*)(dev->dev_addr + 4))[0]);
4688
4689         RT_TRACE(COMP_INIT, "ReadAdapterInfo8192SEFuse(), Permanent Address = %02x-%02x-%02x-%02x-%02x-%02x\n",
4690                         dev->dev_addr[0], dev->dev_addr[1],
4691                         dev->dev_addr[2], dev->dev_addr[3],
4692                         dev->dev_addr[4], dev->dev_addr[5]);
4693
4694         priv->EEPROMBoardType = EEPROM_Default_BoardType;
4695         priv->rf_type = RF_1T2R; //RF_2T2R
4696         priv->EEPROMTxPowerDiff = EEPROM_Default_PwDiff;
4697         priv->EEPROMThermalMeter = EEPROM_Default_ThermalMeter;
4698         priv->EEPROMCrystalCap = EEPROM_Default_CrystalCap;
4699         priv->EEPROMTxPwrBase = EEPROM_Default_TxPowerBase;
4700         priv->EEPROMTSSI_A = EEPROM_Default_TSSI;
4701         priv->EEPROMTSSI_B = EEPROM_Default_TSSI;
4702         priv->EEPROMTxPwrTkMode = EEPROM_Default_TxPwrTkMode;
4703
4704
4705
4706         for (rf_path = 0; rf_path < 2; rf_path++)
4707         {
4708                 for (i = 0; i < 3; i++)
4709                 {
4710                         // Read CCK RF A & B Tx power
4711                         priv->RfCckChnlAreaTxPwr[rf_path][i] =
4712                         priv->RfOfdmChnlAreaTxPwr1T[rf_path][i] =
4713                         priv->RfOfdmChnlAreaTxPwr2T[rf_path][i] =
4714                         (u8)(EEPROM_Default_TxPower & 0xff);
4715                 }
4716         }
4717
4718         for (i = 0; i < 3; i++)
4719         {
4720                 //RT_TRACE((COMP_EFUSE), "CCK RF-%d CHan_Area-%d = 0x%x\n",  rf_path, i,
4721                 //priv->RfCckChnlAreaTxPwr[rf_path][i]);
4722                 //RT_TRACE((COMP_EFUSE), "OFDM-1T RF-%d CHan_Area-%d = 0x%x\n",  rf_path, i,
4723                 //priv->RfOfdmChnlAreaTxPwr1T[rf_path][i]);
4724                 //RT_TRACE((COMP_EFUSE), "OFDM-2T RF-%d CHan_Area-%d = 0x%x\n",  rf_path, i,
4725                 //priv->RfOfdmChnlAreaTxPwr2T[rf_path][i]);
4726         }
4727
4728         // Assign dedicated channel tx power
4729         for(i=0; i<14; i++)     // channel 1~3 use the same Tx Power Level.
4730                 {
4731                 if (i < 3)                      // Cjanel 1-3
4732                         index = 0;
4733                 else if (i < 9)         // Channel 4-9
4734                         index = 1;
4735                 else                            // Channel 10-14
4736                         index = 2;
4737
4738                 // Record A & B CCK /OFDM - 1T/2T Channel area tx power
4739                 priv->RfTxPwrLevelCck[rf_path][i]  =
4740                 priv->RfCckChnlAreaTxPwr[rf_path][index];
4741                 priv->RfTxPwrLevelOfdm1T[rf_path][i]  =
4742                 priv->RfOfdmChnlAreaTxPwr1T[rf_path][index];
4743                 priv->RfTxPwrLevelOfdm2T[rf_path][i]  =
4744                 priv->RfOfdmChnlAreaTxPwr2T[rf_path][index];
4745                 }
4746
4747                 for(i=0; i<14; i++)
4748                 {
4749                 //RT_TRACE((COMP_EFUSE), "Rf-%d TxPwr CH-%d CCK OFDM_1T OFDM_2T= 0x%x/0x%x/0x%x\n",
4750                 //rf_path, i, priv->RfTxPwrLevelCck[0][i],
4751                 //priv->RfTxPwrLevelOfdm1T[0][i] ,
4752                 //priv->RfTxPwrLevelOfdm2T[0][i] );
4753                 }
4754
4755         //
4756         // Update remained HAL variables.
4757         //
4758         priv->TSSI_13dBm = priv->EEPROMThermalMeter *100;
4759         priv->LegacyHTTxPowerDiff = priv->EEPROMTxPowerDiff;//new
4760         priv->TxPowerDiff = priv->EEPROMTxPowerDiff;
4761         //priv->AntennaTxPwDiff[0] = (priv->EEPROMTxPowerDiff & 0xf);// Antenna B gain offset to antenna A, bit0~3
4762         //priv->AntennaTxPwDiff[1] = ((priv->EEPROMTxPowerDiff & 0xf0)>>4);// Antenna C gain offset to antenna A, bit4~7
4763         priv->CrystalCap = priv->EEPROMCrystalCap;      // CrystalCap, bit12~15
4764         priv->ThermalMeter[0] = priv->EEPROMThermalMeter;// ThermalMeter, bit0~3 for RFIC1, bit4~7 for RFIC2
4765         priv->LedStrategy = SW_LED_MODE0;
4766
4767         init_rate_adaptive(dev);
4768
4769         RT_TRACE(COMP_INIT, "<==== ConfigAdapterInfo8192SForAutoLoadFail\n");
4770
4771 }
4772
4773 #if 0
4774 static void rtl8192SU_ReadAdapterInfo8192SEEPROM(struct net_device* dev)
4775 {
4776         u16                             EEPROMId = 0;
4777         u8                              bLoad_From_EEPOM = false;
4778         struct r8192_priv       *priv = ieee80211_priv(dev);
4779         u16                             tmpValue = 0;
4780         u8                              tmpBuffer[30];
4781         int i;
4782
4783         RT_TRACE(COMP_EPROM, "===========>%s()\n", __FUNCTION__);
4784
4785
4786         write_nic_byte(dev, SYS_ISO_CTRL+1, 0xE8); // Isolation signals from Loader
4787         udelay(10000);
4788         write_nic_byte(dev, PMC_FSM, 0x02); // Enable Loader Data Keep
4789
4790
4791         EEPROMId = eprom_read(dev, 0); //first read EEPROM ID out;
4792         RT_TRACE(COMP_EPROM, "EEPROM ID is 0x%x\n", EEPROMId);
4793
4794         if (EEPROMId != RTL8190_EEPROM_ID)
4795         {
4796                 priv->AutoloadFailFlag = true;
4797                 RT_TRACE(COMP_ERR, "EEPROM ID is invalid(is 0x%x(should be 0x%x)\n", EEPROMId, RTL8190_EEPROM_ID);
4798         }
4799         else
4800         {
4801                 priv->AutoloadFailFlag = false;
4802                 bLoad_From_EEPOM = true;
4803         }
4804
4805         if (bLoad_From_EEPOM)
4806         {
4807                 tmpValue = eprom_read(dev, (EEPROM_VID>>1));
4808                 priv->eeprom_vid = endian_swap(&tmpValue);
4809                 priv->eeprom_pid = eprom_read(dev, (EEPROM_PID>>1));
4810
4811                 // Version ID, Channel plan
4812                 tmpValue = eprom_read(dev, (EEPROM_Version>>1));
4813                 //pHalData->card_8192_version = (VERSION_8192S)((usValue&0x00ff));
4814                 priv->eeprom_ChannelPlan =(tmpValue&0xff00)>>8;
4815                 priv->bTXPowerDataReadFromEEPORM = true;
4816
4817                 // Customer ID, 0x00 and 0xff are reserved for Realtek.
4818                 tmpValue = eprom_read(dev, (u16)(EEPROM_CustomID>>1)) ;
4819                 priv->eeprom_CustomerID = (u8)( tmpValue & 0xff);
4820                 priv->eeprom_SubCustomerID = (u8)((tmpValue & 0xff00)>>8);
4821         }
4822         else
4823         {
4824                 priv->eeprom_vid = 0;
4825                 priv->eeprom_pid = 0;
4826                 //priv->card_8192_version = VERSION_8192SU_A;
4827                 priv->eeprom_ChannelPlan = 0;
4828                 priv->eeprom_CustomerID = 0;
4829                 priv->eeprom_SubCustomerID = 0;
4830         }
4831         RT_TRACE(COMP_EPROM, "vid:0x%4x, pid:0x%4x, CustomID:0x%2x, ChanPlan:0x%x\n", priv->eeprom_vid, priv->eeprom_pid, priv->eeprom_CustomerID, priv->eeprom_ChannelPlan);
4832         //set channelplan from eeprom
4833         priv->ChannelPlan = priv->eeprom_ChannelPlan;// FIXLZM
4834
4835         RT_TRACE(COMP_INIT, "EEPROMId = 0x%4x\n", EEPROMId);
4836         RT_TRACE(COMP_INIT, "EEPROM VID = 0x%4x\n", priv->eeprom_vid);
4837         RT_TRACE(COMP_INIT, "EEPROM PID = 0x%4x\n", priv->eeprom_pid);
4838         //RT_TRACE(COMP_INIT, DBG_LOUD, ("EEPROM Version ID: 0x%2x\n", pHalData->VersionID));
4839         RT_TRACE(COMP_INIT, "EEPROM Customer ID: 0x%2x\n", priv->eeprom_CustomerID);
4840         RT_TRACE(COMP_INIT, "EEPROM SubCustomer ID: 0x%2x\n", priv->eeprom_SubCustomerID);
4841         RT_TRACE(COMP_INIT, "EEPROM ChannelPlan = 0x%4x\n", priv->eeprom_ChannelPlan);
4842
4843         // Read USB optional function.
4844         if(bLoad_From_EEPOM)
4845         {
4846                 tmpValue = eprom_read(dev, (EEPROM_USB_OPTIONAL>>1));
4847                 priv->EEPROMUsbOption = (u8)(tmpValue&0xff);
4848         }
4849         else
4850         {
4851                 priv->EEPROMUsbOption = EEPROM_USB_Default_OPTIONAL_FUNC;
4852         }
4853
4854         RT_TRACE(COMP_INIT, "USB Option = %#x\n", priv->EEPROMUsbOption);
4855
4856
4857         if (bLoad_From_EEPOM)
4858         {
4859                 int i;
4860                 for (i=0; i<6; i+=2)
4861                 {
4862                         u16 tmp = 0;
4863                         tmp = eprom_read(dev, (u16)((EEPROM_NODE_ADDRESS_BYTE_0 + i)>>1));
4864                         *(u16*)(&dev->dev_addr[i]) = tmp;
4865                 }
4866         }
4867         else
4868         {
4869                 //<Roger_Notes> In this case, we random assigh MAC address here. 2008.10.15.
4870                 static u8 sMacAddr[6] = {0x00, 0xE0, 0x4C, 0x81, 0x92, 0x00};
4871                 u8      i;
4872
4873                 //sMacAddr[5] = (u8)GetRandomNumber(1, 254);
4874
4875                 for(i = 0; i < 6; i++)
4876                         dev->dev_addr[i] = sMacAddr[i];
4877
4878                 //memcpy(dev->dev_addr, sMacAddr, 6);
4879                 //should I set IDR0 here?
4880         }
4881         write_nic_dword(dev, IDR0, ((u32*)dev->dev_addr)[0]);
4882         write_nic_word(dev, IDR4, ((u16*)(dev->dev_addr + 4))[0]);
4883         RT_TRACE(COMP_EPROM, "MAC addr:"MAC_FMT"\n", MAC_ARG(dev->dev_addr));
4884
4885         priv->rf_type = RTL819X_DEFAULT_RF_TYPE; //default 1T2R
4886 #if (defined (RTL8192SU_FPGA_2MAC_VERIFICATION)||defined (RTL8192SU_ASIC_VERIFICATION))
4887         priv->rf_chip = RF_6052;
4888         priv->rf_type = RTL819X_DEFAULT_RF_TYPE;
4889         //priv->card_8192_version = VERSION_8192SU_A; //Over write for temporally experiment. 2008.10.16. By Roger.
4890 #else
4891         priv->rf_chip = RF_8256;
4892 #endif
4893
4894         {
4895 #if 0
4896                 if(bLoad_From_EEPOM)
4897                 {
4898                         tempval = (ReadEEprom(Adapter, (EEPROM_RFInd_PowerDiff>>1))) & 0xff;
4899                         if (tempval&0x80)       //RF-indication, bit[7]
4900                                 pHalData->RF_Type = RF_1T2R;
4901                         else
4902                                 pHalData->RF_Type = RF_2T4R;
4903                 }
4904 #endif
4905
4906                 priv->EEPROMTxPowerDiff = EEPROM_Default_TxPowerDiff;
4907                 RT_TRACE(COMP_INIT, "TxPowerDiff = %#x\n", priv->EEPROMTxPowerDiff);
4908
4909
4910                 //
4911                 // Read antenna tx power offset of B/C/D to A  from EEPROM
4912                 // and read ThermalMeter from EEPROM
4913                 //
4914                 if(bLoad_From_EEPOM)
4915                 {
4916                         tmpValue = eprom_read(dev, (EEPROM_PwDiff>>1));
4917                         priv->EEPROMPwDiff = tmpValue&0x00ff;
4918                         priv->EEPROMThermalMeter = (tmpValue&0xff00)>>8;
4919                 }
4920                 else
4921                 {
4922                         priv->EEPROMPwDiff = EEPROM_Default_PwDiff;
4923                         priv->EEPROMThermalMeter = EEPROM_Default_ThermalMeter;
4924                 }
4925                 RT_TRACE(COMP_INIT, "PwDiff = %#x\n", priv->EEPROMPwDiff);
4926                 RT_TRACE(COMP_INIT, "ThermalMeter = %#x\n", priv->EEPROMThermalMeter);
4927
4928                 priv->TSSI_13dBm = priv->EEPROMThermalMeter *100;
4929
4930
4931                 // Read CrystalCap from EEPROM
4932                 if(bLoad_From_EEPOM)
4933                 {
4934                         priv->EEPROMCrystalCap =(u8) (((eprom_read(dev, (EEPROM_CrystalCap>>1)))&0xf000)>>12);
4935                 }
4936                 else
4937                 {
4938                         priv->EEPROMCrystalCap = EEPROM_Default_CrystalCap;
4939                 }
4940                 RT_TRACE(COMP_INIT, "CrystalCap = %#x\n", priv->EEPROMCrystalCap);
4941
4942
4943                 //if(pHalData->EEPROM_Def_Ver == 0)     // old eeprom definition
4944                 {
4945
4946                         //
4947                         // Get Tx Power Base.//===>
4948                         //
4949                         if(bLoad_From_EEPOM)
4950                         {
4951                                 priv->EEPROMTxPwrBase =(u8) ((eprom_read(dev, (EEPROM_TxPowerBase>>1)))&0xff);
4952                         }
4953                         else
4954                         {
4955                                 priv->EEPROMTxPwrBase = EEPROM_Default_TxPowerBase;
4956                         }
4957
4958                         RT_TRACE(COMP_INIT, "TxPwrBase = %#x\n", priv->EEPROMTxPwrBase);
4959
4960                         //
4961                         // Get CustomerID(Boad Type)
4962                         // i.e., 0x0: RTL8188SU, 0x1: RTL8191SU, 0x2: RTL8192SU, 0x3: RTL8191GU.
4963                         // Others: Reserved. Default is 0x2: RTL8192SU.
4964                         //
4965                         if(bLoad_From_EEPOM)
4966                         {
4967                                 tmpValue = eprom_read(dev, (u16) (EEPROM_BoardType>>1));
4968                                 priv->EEPROMBoardType = (u8)(tmpValue&0xff);
4969                         }
4970                         else
4971                         {
4972                                 priv->EEPROMBoardType = EEPROM_Default_BoardType;
4973                         }
4974
4975                         RT_TRACE(COMP_INIT, "BoardType = %#x\n", priv->EEPROMBoardType);
4976
4977                         // Please add code in the section!!!!
4978                         // And merge tx power difference section.
4979
4980                         //
4981                         // Get TSSI value for each path.
4982                         //
4983                         if(bLoad_From_EEPOM)
4984                         {
4985                                 tmpValue = eprom_read(dev, (u16) ((EEPROM_TSSI_A)>>1));
4986                                 priv->EEPROMTSSI_A = (u8)((tmpValue&0xff00)>>8);
4987                         }
4988                         else
4989                         { // Default setting for Empty EEPROM
4990                                 priv->EEPROMTSSI_A = EEPROM_Default_TSSI;
4991                         }
4992
4993                         if(bLoad_From_EEPOM)
4994                         {
4995                                 tmpValue = eprom_read(dev, (u16) ((EEPROM_TSSI_B)>>1));
4996                                 priv->EEPROMTSSI_B = (u8)(tmpValue&0xff);
4997                                 priv->EEPROMTxPwrTkMode = (u8)((tmpValue&0xff00)>>8);
4998                         }
4999                         else
5000                         { // Default setting for Empty EEPROM
5001                                 priv->EEPROMTSSI_B = EEPROM_Default_TSSI;
5002                                 priv->EEPROMTxPwrTkMode = EEPROM_Default_TxPwrTkMode;
5003                         }
5004
5005                         RT_TRACE(COMP_INIT, "TSSI_A = %#x, TSSI_B = %#x\n", priv->EEPROMTSSI_A, priv->EEPROMTSSI_B);
5006                         RT_TRACE(COMP_INIT, "TxPwrTkMod = %#x\n", priv->EEPROMTxPwrTkMode);
5007
5008
5009                 }
5010
5011
5012                 priv->TxPowerDiff = priv->EEPROMPwDiff;
5013                 // Antenna B gain offset to antenna A, bit0~3
5014                 priv->AntennaTxPwDiff[0] = (priv->EEPROMTxPowerDiff & 0xf);
5015                 // Antenna C gain offset to antenna A, bit4~7
5016                 priv->AntennaTxPwDiff[1] = ((priv->EEPROMTxPowerDiff & 0xf0)>>4);
5017                 // CrystalCap, bit12~15
5018                 priv->CrystalCap = priv->EEPROMCrystalCap;
5019                 // ThermalMeter, bit0~3 for RFIC1, bit4~7 for RFIC2
5020                 // 92U does not enable TX power tracking.
5021                 priv->ThermalMeter[0] = priv->EEPROMThermalMeter;
5022         }
5023
5024         priv->LedStrategy = SW_LED_MODE0;
5025
5026         if(priv->rf_type == RF_1T2R)
5027         {
5028                 RT_TRACE(COMP_EPROM, "\n1T2R config\n");
5029         }
5030         else
5031         {
5032                 RT_TRACE(COMP_EPROM, "\n2T4R config\n");
5033         }
5034
5035         // 2008/01/16 MH We can only know RF type in the function. So we have to init
5036         // DIG RATR table again.
5037         init_rate_adaptive(dev);
5038         //we need init DIG RATR table here again.
5039
5040         RT_TRACE(COMP_EPROM, "<===========%s()\n", __FUNCTION__);
5041         return;
5042 }
5043
5044 //
5045 //      Description:
5046 //              1. Read HW adapter information by E-Fuse.
5047 //              2. Refered from SD1 Richard.
5048 //
5049 //      Assumption:
5050 //              1. Boot from E-Fuse and CR9346 regiser has verified.
5051 //              2. PASSIVE_LEVEL (USB interface)
5052 //
5053 //      Created by Roger, 2008.10.21.
5054 //
5055 void
5056 rtl8192SU_ReadAdapterInfo8192SEFuse(struct net_device* dev)
5057 {
5058         struct r8192_priv       *priv = ieee80211_priv(dev);
5059         u16                     i,usValue;
5060         u16                     EEPROMId;
5061         u8                      readbyte;
5062         u8                      OFDMTxPwr[14];
5063         u8                      CCKTxPwr[14];
5064         u8                      HT2T_TxPwr[6];
5065         u8                      UsbPhyParam[5];
5066         u8                      hwinfo[HWSET_MAX_SIZE_92S];
5067
5068
5069         RT_TRACE(COMP_INIT, "====> ReadAdapterInfo8192SEFuse\n");
5070
5071         //
5072         // <Roger_Notes> We set Isolation signals from Loader and reset EEPROM after system resuming
5073         // from suspend mode.
5074         // 2008.10.21.
5075         //
5076         write_nic_byte(dev, SYS_ISO_CTRL+1, 0xE8); // Isolation signals from Loader
5077         //PlatformStallExecution(10000);
5078         mdelay(10);
5079         write_nic_byte(dev, SYS_FUNC_EN+1, 0x40);
5080         write_nic_byte(dev, SYS_FUNC_EN+1, 0x50);
5081
5082         readbyte = read_nic_byte(dev, EFUSE_TEST+3);
5083         write_nic_byte(dev, EFUSE_TEST+3, (readbyte | 0x80));
5084         write_nic_byte(dev, EFUSE_TEST+3, 0x72);
5085         write_nic_byte(dev, EFUSE_CLK, 0x03);
5086
5087         //
5088         // Dump EFUSe at init time for later use
5089         //
5090         // Read EFUSE real map to shadow!!
5091         EFUSE_ShadowMapUpdate(dev);
5092
5093         memcpy(hwinfo, (void*)&priv->EfuseMap[EFUSE_INIT_MAP][0], HWSET_MAX_SIZE_92S);
5094         //RT_PRINT_DATA(COMP_INIT, DBG_LOUD, ("MAP \n"), hwinfo, HWSET_MAX_SIZE_92S);
5095
5096         //
5097         // <Roger_Notes> Event though CR9346 regiser can verify whether Autoload is success or not, but we still
5098         // double check ID codes for 92S here(e.g., due to HW GPIO polling fail issue).
5099         // 2008.10.21.
5100         //
5101         ReadEFuse(dev, 0, 2, (unsigned char*) &EEPROMId);
5102
5103         if( EEPROMId != RTL8190_EEPROM_ID )
5104         {
5105                 RT_TRACE(COMP_INIT, "EEPROM ID(%#x) is invalid!!\n", EEPROMId);
5106                 priv->AutoloadFailFlag=true;
5107         }
5108         else
5109         {
5110                 priv->AutoloadFailFlag=false;
5111         }
5112
5113        // Read IC Version && Channel Plan
5114         if(!priv->AutoloadFailFlag)
5115         {
5116
5117                 // VID, PID
5118                 ReadEFuse(dev, EEPROM_VID, 2, (unsigned char*) &priv->eeprom_vid);
5119                 ReadEFuse(dev, EEPROM_PID, 2, (unsigned char*) &priv->eeprom_pid);
5120
5121                 // Version ID, Channel plan
5122                 ReadEFuse(dev, EEPROM_Version, 2, (unsigned char*) &usValue);
5123                 //pHalData->VersionID = (VERSION_8192S)(usValue&0x00ff);
5124                 priv->eeprom_ChannelPlan = (usValue&0xff00>>8);
5125                 priv->bTXPowerDataReadFromEEPORM = true;
5126
5127                 // Customer ID, 0x00 and 0xff are reserved for Realtek.
5128                 ReadEFuse(dev, EEPROM_CustomID, 2, (unsigned char*) &usValue);
5129                 priv->eeprom_CustomerID = (u8)( usValue & 0xff);
5130                 priv->eeprom_SubCustomerID = (u8)((usValue & 0xff00)>>8);
5131         }
5132         else
5133         {
5134                 priv->eeprom_vid = 0;
5135                 priv->eeprom_pid = 0;
5136                 priv->eeprom_ChannelPlan = 0;
5137                 priv->eeprom_CustomerID = 0;
5138                 priv->eeprom_SubCustomerID = 0;
5139         }
5140
5141         RT_TRACE(COMP_INIT, "EEPROM Id = 0x%4x\n", EEPROMId);
5142         RT_TRACE(COMP_INIT, "EEPROM VID = 0x%4x\n", priv->eeprom_vid);
5143         RT_TRACE(COMP_INIT, "EEPROM PID = 0x%4x\n", priv->eeprom_pid);
5144         //RT_TRACE(COMP_INIT, DBG_LOUD, ("EEPROM Version ID: 0x%2x\n", pHalData->VersionID));
5145         RT_TRACE(COMP_INIT, "EEPROM Customer ID: 0x%2x\n", priv->eeprom_CustomerID);
5146         RT_TRACE(COMP_INIT, "EEPROM SubCustomer ID: 0x%2x\n", priv->eeprom_SubCustomerID);
5147         RT_TRACE(COMP_INIT, "EEPROM ChannelPlan = 0x%4x\n", priv->eeprom_ChannelPlan);
5148
5149
5150         // Read USB optional function.
5151         if(!priv->AutoloadFailFlag)
5152         {
5153                 ReadEFuse(dev, EEPROM_USB_OPTIONAL, 1, (unsigned char*) &priv->EEPROMUsbOption);
5154         }
5155         else
5156         {
5157                 priv->EEPROMUsbOption = EEPROM_USB_Default_OPTIONAL_FUNC;
5158         }
5159
5160         RT_TRACE(COMP_INIT, "USB Option = %#x\n", priv->EEPROMUsbOption);
5161
5162
5163         // Read USB PHY parameters.
5164         if(!priv->AutoloadFailFlag)
5165         {
5166                 ReadEFuse(dev, EEPROM_USB_PHY_PARA1, 5, (unsigned char*)UsbPhyParam);
5167                 for(i=0; i<5; i++)
5168                 {
5169                         priv->EEPROMUsbPhyParam[i] = UsbPhyParam[i];
5170                         RT_TRACE(COMP_INIT, "USB Param = index(%d) = %#x\n", i, priv->EEPROMUsbPhyParam[i]);
5171                 }
5172         }
5173         else
5174         {
5175                 for(i=0; i<5; i++)
5176                 {
5177                         priv->EEPROMUsbPhyParam[i] = EEPROM_USB_Default_PHY_PARAM;
5178                         RT_TRACE(COMP_INIT, "USB Param = index(%d) = %#x\n", i, priv->EEPROMUsbPhyParam[i]);
5179                 }
5180         }
5181
5182
5183        //Read Permanent MAC address
5184         if(!priv->AutoloadFailFlag)
5185         {
5186                 u8                      macaddr[6] = {0x00, 0xe1, 0x86, 0x4c, 0x92, 0x00};
5187
5188                 ReadEFuse(dev, EEPROM_NODE_ADDRESS_BYTE_0, 6, (unsigned char*)macaddr);
5189                 for(i=0; i<6; i++)
5190                         dev->dev_addr[i] = macaddr[i];
5191         }
5192         else
5193         {//Auto load fail
5194
5195                 //<Roger_Notes> In this case, we random assigh MAC address here. 2008.10.15.
5196                 static u8 sMacAddr[6] = {0x00, 0xE0, 0x4C, 0x81, 0x92, 0x00};
5197                 u8      i;
5198
5199                 //if(!Adapter->bInHctTest)
5200                     //sMacAddr[5] = (u8)GetRandomNumber(1, 254);
5201
5202                 for(i = 0; i < 6; i++)
5203                         dev->dev_addr[i] = sMacAddr[i];
5204         }
5205
5206         //NicIFSetMacAddress(Adapter, Adapter->PermanentAddress);
5207         write_nic_dword(dev, IDR0, ((u32*)dev->dev_addr)[0]);
5208         write_nic_word(dev, IDR4, ((u16*)(dev->dev_addr + 4))[0]);
5209
5210         RT_TRACE(COMP_INIT, "ReadAdapterInfo8192SEFuse(), Permanent Address = %02x-%02x-%02x-%02x-%02x-%02x\n",
5211                         dev->dev_addr[0], dev->dev_addr[1],
5212                         dev->dev_addr[2], dev->dev_addr[3],
5213                         dev->dev_addr[4], dev->dev_addr[5]);
5214
5215         // 2007/11/15 MH For RTL8192USB we assign as 1T2R now.
5216         priv->rf_type = RTL819X_DEFAULT_RF_TYPE;        // default : 1T2R
5217
5218 #if (defined (RTL8192SU_FPGA_2MAC_VERIFICATION)||defined (RTL8192SU_ASIC_VERIFICATION))
5219         priv->rf_chip = RF_6052;
5220         priv->rf_type = RTL819X_DEFAULT_RF_TYPE;
5221 #else
5222         priv->rf_chip = RF_8256;
5223 #endif
5224
5225         {
5226                 //
5227                 // Read antenna tx power offset of B/C/D to A  from EEPROM
5228                 // and read ThermalMeter from EEPROM
5229                 //
5230                 if(!priv->AutoloadFailFlag)
5231                 {
5232                         ReadEFuse(dev, EEPROM_PwDiff, 2, (unsigned char*) &usValue);
5233                         priv->EEPROMPwDiff = usValue&0x00ff;
5234                         priv->EEPROMThermalMeter = (usValue&0xff00)>>8;
5235                 }
5236                 else
5237                 {
5238                         priv->EEPROMPwDiff = EEPROM_Default_PwDiff;
5239                         priv->EEPROMThermalMeter = EEPROM_Default_ThermalMeter;
5240                 }
5241
5242                 RT_TRACE(COMP_INIT, "PwDiff = %#x\n", priv->EEPROMPwDiff);
5243                 RT_TRACE(COMP_INIT, "ThermalMeter = %#x\n", priv->EEPROMThermalMeter);
5244
5245                 priv->TSSI_13dBm = priv->EEPROMThermalMeter *100;
5246
5247                 //
5248                 // Read Tx Power gain offset of legacy OFDM to HT rate.
5249                 // Read CrystalCap from EEPROM
5250                 //
5251                 if(!priv->AutoloadFailFlag)
5252                 {
5253                         ReadEFuse(dev, EEPROM_CrystalCap, 1, (unsigned char*) &usValue);
5254                         priv->EEPROMCrystalCap = (u8)((usValue&0xf0)>>4);
5255                 }
5256                 else
5257                 {
5258                         priv->EEPROMCrystalCap = EEPROM_Default_CrystalCap;
5259                 }
5260
5261                 RT_TRACE(COMP_INIT, "CrystalCap = %#x\n", priv->EEPROMCrystalCap);
5262
5263                 priv->EEPROMTxPowerDiff = EEPROM_Default_TxPowerDiff;
5264                 RT_TRACE(COMP_INIT, "TxPowerDiff = %d\n", priv->EEPROMTxPowerDiff);
5265
5266
5267                 //
5268                 // Get Tx Power Base.
5269                 //
5270                 if(!priv->AutoloadFailFlag)
5271                 {
5272                         ReadEFuse(dev, EEPROM_TxPowerBase, 1, (unsigned char*) &priv->EEPROMTxPwrBase );
5273                 }
5274                 else
5275                 {
5276                         priv->EEPROMTxPwrBase = EEPROM_Default_TxPowerBase;
5277                 }
5278
5279                 RT_TRACE(COMP_INIT, "TxPwrBase = %#x\n", priv->EEPROMTxPwrBase);
5280
5281                 //
5282                 // Get CustomerID(Boad Type)
5283                 // i.e., 0x0: RTL8188SU, 0x1: RTL8191SU, 0x2: RTL8192SU, 0x3: RTL8191GU.
5284                 // Others: Reserved. Default is 0x2: RTL8192SU.
5285                 //
5286                 if(!priv->AutoloadFailFlag)
5287                 {
5288                         ReadEFuse(dev, EEPROM_BoardType, 1, (unsigned char*) &priv->EEPROMBoardType );
5289                 }
5290                 else
5291                 {
5292                         priv->EEPROMBoardType = EEPROM_Default_BoardType;
5293                 }
5294
5295                 RT_TRACE(COMP_INIT, "BoardType = %#x\n", priv->EEPROMBoardType);
5296
5297                 //if(pHalData->EEPROM_Def_Ver == 0)
5298                 {
5299                         // Please add code in the section!!!!
5300                         // And merge tx power difference section.
5301
5302                         //
5303                         // Get TSSI value for each path.
5304                         //
5305                         if(!priv->AutoloadFailFlag)
5306                         {
5307                                 ReadEFuse(dev, EEPROM_TSSI_A, 2, (unsigned char*)&usValue);
5308                                 priv->EEPROMTSSI_A = (u8)(usValue&0xff);
5309                                 priv->EEPROMTSSI_B = (u8)((usValue&0xff00)>>8);
5310                         }
5311                         else
5312                         { // Default setting for Empty EEPROM
5313                                 priv->EEPROMTSSI_A = EEPROM_Default_TSSI;
5314                                 priv->EEPROMTSSI_B = EEPROM_Default_TSSI;
5315                         }
5316
5317                         RT_TRACE(COMP_INIT, "TSSI_A = %#x, TSSI_B = %#x\n",
5318                                         priv->EEPROMTSSI_A, priv->EEPROMTSSI_B);
5319
5320                         //
5321                         // Get Tx Power tracking mode.
5322                         //
5323                         if(!priv->AutoloadFailFlag)
5324                         {
5325                                 ReadEFuse(dev, EEPROM_TxPwTkMode, 1, (unsigned char*)&priv->EEPROMTxPwrTkMode);
5326                         }
5327                         else
5328                         { // Default setting for Empty EEPROM
5329                                 priv->EEPROMTxPwrTkMode = EEPROM_Default_TxPwrTkMode;
5330                         }
5331
5332                         RT_TRACE(COMP_INIT, "TxPwrTkMod = %#x\n", priv->EEPROMTxPwrTkMode);
5333
5334
5335                         // TODO: The following HT 2T Path A and B Power Index should be updated.!! Added by Roger, 2008.20.23.
5336
5337                         //
5338                         // Get HT 2T Path A and B Power Index.
5339                         //
5340                         if(!priv->AutoloadFailFlag)
5341                         {
5342                                 ReadEFuse(dev, EEPROM_HT2T_CH1_A, 6, (unsigned char*)HT2T_TxPwr);
5343                                 for(i=0; i<6; i++)
5344                                 {
5345                                         priv->EEPROMHT2T_TxPwr[i] = HT2T_TxPwr[i];
5346                                 }
5347                         }
5348                         else
5349                         { // Default setting for Empty EEPROM
5350                                 for(i=0; i<6; i++)
5351                                 {
5352                                         priv->EEPROMHT2T_TxPwr[i] = EEPROM_Default_HT2T_TxPwr;
5353                                 }
5354                         }
5355
5356                         for(i=0; i<6; i++)
5357                         {
5358                                 RT_TRACE(COMP_INIT, "EEPROMHT2T_TxPwr, Index %d = 0x%02x\n",
5359                                                 i, priv->EEPROMHT2T_TxPwr[i]);
5360                         }
5361                 }
5362
5363
5364                 priv->TxPowerDiff = priv->EEPROMPwDiff;
5365                 // Antenna B gain offset to antenna A, bit0~3
5366                 priv->AntennaTxPwDiff[0] = (priv->EEPROMTxPowerDiff & 0xf);
5367                 // Antenna C gain offset to antenna A, bit4~7
5368                 priv->AntennaTxPwDiff[1] = ((priv->EEPROMTxPowerDiff & 0xf0)>>4);
5369                 // CrystalCap, bit12~15
5370                 priv->CrystalCap = priv->EEPROMCrystalCap;
5371                 // ThermalMeter, bit0~3 for RFIC1, bit4~7 for RFIC2
5372                 // 92U does not enable TX power tracking.
5373                 priv->ThermalMeter[0] = priv->EEPROMThermalMeter;
5374         }
5375
5376         priv->LedStrategy = SW_LED_MODE0;
5377
5378         init_rate_adaptive(dev);
5379
5380         RT_TRACE(COMP_INIT, "<==== ReadAdapterInfo8192SEFuse\n");
5381
5382 }
5383 #endif
5384
5385 //
5386 //      Description:
5387 //              Read HW adapter information by E-Fuse or EEPROM according CR9346 reported.
5388 //
5389 //      Assumption:
5390 //              1. CR9346 regiser has verified.
5391 //              2. PASSIVE_LEVEL (USB interface)
5392 //
5393 //      Created by Roger, 2008.10.21.
5394 //
5395 void
5396 rtl8192SU_ReadAdapterInfo8192SUsb(struct net_device* dev)
5397 {
5398         struct r8192_priv       *priv = ieee80211_priv(dev);
5399         u16                     i,usValue;
5400         u8                      tmpU1b, tempval;
5401         u16                     EEPROMId;
5402         u8                      hwinfo[HWSET_MAX_SIZE_92S];
5403         u8                      rf_path, index; // For EEPROM/EFUSE After V0.6_1117
5404
5405
5406         RT_TRACE(COMP_INIT, "====> ReadAdapterInfo8192SUsb\n");
5407
5408         //
5409         // <Roger_Note> The following operation are prevent Efuse leakage by turn on 2.5V.
5410         // 2008.11.25.
5411         //
5412         tmpU1b = read_nic_byte(dev, EFUSE_TEST+3);
5413         write_nic_byte(dev, EFUSE_TEST+3, tmpU1b|0x80);
5414         //PlatformStallExecution(1000);
5415         mdelay(10);
5416         write_nic_byte(dev, EFUSE_TEST+3, (tmpU1b&(~BIT7)));
5417
5418         // Retrieve Chip version.
5419         priv->card_8192_version = (VERSION_8192S)((read_nic_dword(dev, PMC_FSM)>>16)&0xF);
5420         RT_TRACE(COMP_INIT, "Chip Version ID: 0x%2x\n", priv->card_8192_version);
5421
5422         switch(priv->card_8192_version)
5423         {
5424                 case 0:
5425                         RT_TRACE(COMP_INIT, "Chip Version ID: VERSION_8192S_ACUT.\n");
5426                         break;
5427                 case 1:
5428                         RT_TRACE(COMP_INIT, "Chip Version ID: VERSION_8192S_BCUT.\n");
5429                         break;
5430                 case 2:
5431                         RT_TRACE(COMP_INIT, "Chip Version ID: VERSION_8192S_CCUT.\n");
5432                         break;
5433                 default:
5434                         RT_TRACE(COMP_INIT, "Unknown Chip Version!!\n");
5435                         priv->card_8192_version = VERSION_8192S_BCUT;
5436                         break;
5437         }
5438
5439         //if (IS_BOOT_FROM_EEPROM(Adapter))
5440         if(priv->EepromOrEfuse)
5441         {       // Read frin EEPROM
5442                 write_nic_byte(dev, SYS_ISO_CTRL+1, 0xE8); // Isolation signals from Loader
5443                 //PlatformStallExecution(10000);
5444                 mdelay(10);
5445                 write_nic_byte(dev, PMC_FSM, 0x02); // Enable Loader Data Keep
5446                 // Read all Content from EEPROM or EFUSE.
5447                 for(i = 0; i < HWSET_MAX_SIZE_92S; i += 2)
5448                 {
5449                         usValue = eprom_read(dev, (u16) (i>>1));
5450                         *((u16*)(&hwinfo[i])) = usValue;
5451                 }
5452         }
5453         else if (!(priv->EepromOrEfuse))
5454         {       // Read from EFUSE
5455
5456                 //
5457                 // <Roger_Notes> We set Isolation signals from Loader and reset EEPROM after system resuming
5458                 // from suspend mode.
5459                 // 2008.10.21.
5460                 //
5461                 //PlatformEFIOWrite1Byte(Adapter, SYS_ISO_CTRL+1, 0xE8); // Isolation signals from Loader
5462                 //PlatformStallExecution(10000);
5463                 //PlatformEFIOWrite1Byte(Adapter, SYS_FUNC_EN+1, 0x40);
5464                 //PlatformEFIOWrite1Byte(Adapter, SYS_FUNC_EN+1, 0x50);
5465
5466                 //tmpU1b = PlatformEFIORead1Byte(Adapter, EFUSE_TEST+3);
5467                 //PlatformEFIOWrite1Byte(Adapter, EFUSE_TEST+3, (tmpU1b | 0x80));
5468                 //PlatformEFIOWrite1Byte(Adapter, EFUSE_TEST+3, 0x72);
5469                 //PlatformEFIOWrite1Byte(Adapter, EFUSE_CLK, 0x03);
5470
5471                 // Read EFUSE real map to shadow.
5472                 EFUSE_ShadowMapUpdate(dev);
5473                 memcpy(hwinfo, &priv->EfuseMap[EFUSE_INIT_MAP][0], HWSET_MAX_SIZE_92S);
5474         }
5475         else
5476         {
5477                 RT_TRACE(COMP_INIT, "ReadAdapterInfo8192SUsb(): Invalid boot type!!\n");
5478         }
5479
5480         //YJ,test,090106
5481         //dump_buf(hwinfo,HWSET_MAX_SIZE_92S);
5482         //
5483         // <Roger_Notes> The following are EFUSE/EEPROM independent operations!!
5484         //
5485         //RT_PRINT_DATA(COMP_EFUSE, DBG_LOUD, ("MAP: \n"), hwinfo, HWSET_MAX_SIZE_92S);
5486
5487         //
5488         // <Roger_Notes> Event though CR9346 regiser can verify whether Autoload is success or not, but we still
5489         // double check ID codes for 92S here(e.g., due to HW GPIO polling fail issue).
5490         // 2008.10.21.
5491         //
5492         EEPROMId = *((u16 *)&hwinfo[0]);
5493
5494         if( EEPROMId != RTL8190_EEPROM_ID )
5495         {
5496                 RT_TRACE(COMP_INIT, "ID(%#x) is invalid!!\n", EEPROMId);
5497                 priv->bTXPowerDataReadFromEEPORM = FALSE;
5498                 priv->AutoloadFailFlag=TRUE;
5499         }
5500         else
5501         {
5502                 priv->AutoloadFailFlag=FALSE;
5503                 priv->bTXPowerDataReadFromEEPORM = TRUE;
5504         }
5505        // Read IC Version && Channel Plan
5506         if(!priv->AutoloadFailFlag)
5507         {
5508                 // VID, PID
5509                 priv->eeprom_vid = *(u16 *)&hwinfo[EEPROM_VID];
5510                 priv->eeprom_pid = *(u16 *)&hwinfo[EEPROM_PID];
5511                 priv->bIgnoreDiffRateTxPowerOffset = false;     //cosa for test
5512
5513
5514                 // EEPROM Version ID, Channel plan
5515                 priv->EEPROMVersion = *(u8 *)&hwinfo[EEPROM_Version];
5516                 priv->eeprom_ChannelPlan = *(u8 *)&hwinfo[EEPROM_ChannelPlan];
5517
5518                 // Customer ID, 0x00 and 0xff are reserved for Realtek.
5519                 priv->eeprom_CustomerID = *(u8 *)&hwinfo[EEPROM_CustomID];
5520                 priv->eeprom_SubCustomerID = *(u8 *)&hwinfo[EEPROM_SubCustomID];
5521         }
5522         else
5523         {
5524                 //priv->eeprom_vid = 0;
5525                 //priv->eeprom_pid = 0;
5526                 //priv->EEPROMVersion = 0;
5527                 //priv->eeprom_ChannelPlan = 0;
5528                 //priv->eeprom_CustomerID = 0;
5529                 //priv->eeprom_SubCustomerID = 0;
5530
5531                 rtl8192SU_ConfigAdapterInfo8192SForAutoLoadFail(dev);
5532                 return;
5533         }
5534
5535
5536         RT_TRACE(COMP_INIT, "EEPROM Id = 0x%4x\n", EEPROMId);
5537         RT_TRACE(COMP_INIT, "EEPROM VID = 0x%4x\n", priv->eeprom_vid);
5538         RT_TRACE(COMP_INIT, "EEPROM PID = 0x%4x\n", priv->eeprom_pid);
5539         RT_TRACE(COMP_INIT, "EEPROM Version ID: 0x%2x\n", priv->EEPROMVersion);
5540         RT_TRACE(COMP_INIT, "EEPROM Customer ID: 0x%2x\n", priv->eeprom_CustomerID);
5541         RT_TRACE(COMP_INIT, "EEPROM SubCustomer ID: 0x%2x\n", priv->eeprom_SubCustomerID);
5542         RT_TRACE(COMP_INIT, "EEPROM ChannelPlan = 0x%4x\n", priv->eeprom_ChannelPlan);
5543         RT_TRACE(COMP_INIT, "bIgnoreDiffRateTxPowerOffset = %d\n", priv->bIgnoreDiffRateTxPowerOffset);
5544
5545
5546         // Read USB optional function.
5547         if(!priv->AutoloadFailFlag)
5548         {
5549                 priv->EEPROMUsbOption = *(u8 *)&hwinfo[EEPROM_USB_OPTIONAL];
5550         }
5551         else
5552         {
5553                 priv->EEPROMUsbOption = EEPROM_USB_Default_OPTIONAL_FUNC;
5554         }
5555
5556
5557         priv->EEPROMUsbEndPointNumber = rtl8192SU_UsbOptionToEndPointNumber((priv->EEPROMUsbOption&EEPROM_EP_NUMBER)>>3);
5558
5559         RT_TRACE(COMP_INIT, "USB Option = %#x\n", priv->EEPROMUsbOption);
5560         RT_TRACE(COMP_INIT, "EndPoint Number = %#x\n", priv->EEPROMUsbEndPointNumber);
5561
5562 #ifdef TO_DO_LIST
5563         //
5564         //  Decide CustomerID according to VID/DID or EEPROM
5565         //
5566         switch(pHalData->EEPROMCustomerID)
5567         {
5568                 case EEPROM_CID_ALPHA:
5569                         pMgntInfo->CustomerID = RT_CID_819x_ALPHA;
5570                         break;
5571
5572                 case EEPROM_CID_CAMEO:
5573                         pMgntInfo->CustomerID = RT_CID_819x_CAMEO;
5574                         break;
5575
5576                 case EEPROM_CID_SITECOM:
5577                         pMgntInfo->CustomerID = RT_CID_819x_Sitecom;
5578                         RT_TRACE(COMP_INIT, DBG_LOUD, ("CustomerID = 0x%4x\n", pMgntInfo->CustomerID));
5579
5580                         break;
5581
5582                 case EEPROM_CID_WHQL:
5583                         Adapter->bInHctTest = TRUE;
5584
5585                         pMgntInfo->bSupportTurboMode = FALSE;
5586                         pMgntInfo->bAutoTurboBy8186 = FALSE;
5587
5588                         pMgntInfo->PowerSaveControl.bInactivePs = FALSE;
5589                         pMgntInfo->PowerSaveControl.bIPSModeBackup = FALSE;
5590                         pMgntInfo->PowerSaveControl.bLeisurePs = FALSE;
5591                         pMgntInfo->keepAliveLevel = 0;
5592                         break;
5593
5594                 default:
5595                         pMgntInfo->CustomerID = RT_CID_DEFAULT;
5596                         break;
5597
5598         }
5599
5600         //
5601         // Led mode
5602         //
5603         switch(pMgntInfo->CustomerID)
5604         {
5605                 case RT_CID_DEFAULT:
5606                 case RT_CID_819x_ALPHA:
5607                         pHalData->LedStrategy = SW_LED_MODE1;
5608                         pHalData->bRegUseLed = TRUE;
5609                         pHalData->SwLed1.bLedOn = TRUE;
5610                         break;
5611                 case RT_CID_819x_CAMEO:
5612                         pHalData->LedStrategy = SW_LED_MODE1;
5613                         pHalData->bRegUseLed = TRUE;
5614                         break;
5615
5616                 case RT_CID_819x_Sitecom:
5617                         pHalData->LedStrategy = SW_LED_MODE2;
5618                         pHalData->bRegUseLed = TRUE;
5619                         break;
5620
5621                 default:
5622                         pHalData->LedStrategy = SW_LED_MODE0;
5623                         break;
5624         }
5625 #endif
5626
5627         // Read USB PHY parameters.
5628         for(i=0; i<5; i++)
5629                 priv->EEPROMUsbPhyParam[i] = *(u8 *)&hwinfo[EEPROM_USB_PHY_PARA1+i];
5630
5631         //RT_PRINT_DATA(COMP_EFUSE, DBG_LOUD, ("USB PHY Param: \n"), pHalData->EEPROMUsbPhyParam, 5);
5632
5633
5634        //Read Permanent MAC address
5635         for(i=0; i<6; i++)
5636                 dev->dev_addr[i] =  *(u8 *)&hwinfo[EEPROM_NODE_ADDRESS_BYTE_0+i];
5637
5638         //NicIFSetMacAddress(Adapter, Adapter->PermanentAddress);
5639         write_nic_dword(dev, IDR0, ((u32*)dev->dev_addr)[0]);
5640         write_nic_word(dev, IDR4, ((u16*)(dev->dev_addr + 4))[0]);
5641
5642         RT_TRACE(COMP_INIT, "ReadAdapterInfo8192SEFuse(), Permanent Address = %02x-%02x-%02x-%02x-%02x-%02x\n",
5643                         dev->dev_addr[0], dev->dev_addr[1],
5644                         dev->dev_addr[2], dev->dev_addr[3],
5645                         dev->dev_addr[4], dev->dev_addr[5]);
5646
5647         //
5648         // Get CustomerID(Boad Type)
5649         // i.e., 0x0: RTL8188SU, 0x1: RTL8191SU, 0x2: RTL8192SU, 0x3: RTL8191GU.
5650         // Others: Reserved. Default is 0x2: RTL8192SU.
5651         //
5652         //if(!priv->AutoloadFailFlag)
5653         //{
5654                 priv->EEPROMBoardType = *(u8 *)&hwinfo[EEPROM_BoardType];
5655                 priv->rf_type = rtl8192SU_BoardTypeToRFtype(dev, priv->EEPROMBoardType);
5656         //}
5657         //else
5658         //{
5659         //      priv->EEPROMBoardType = EEPROM_Default_BoardType;
5660         //      priv->rf_type = RF_1T2R;
5661         //}
5662
5663 #if (defined (RTL8192SU_FPGA_2MAC_VERIFICATION)||defined (RTL8192SU_ASIC_VERIFICATION))
5664         priv->rf_chip = RF_6052;
5665 #else
5666         priv->rf_chip = RF_8256;
5667 #endif
5668
5669         priv->rf_chip = RF_6052;//lzm test
5670         RT_TRACE(COMP_INIT, "BoardType = 0x%2x\n", priv->EEPROMBoardType);
5671         RT_TRACE(COMP_INIT, "RF_Type = 0x%2x\n", priv->rf_type);
5672
5673         //
5674         // Read antenna tx power offset of B/C/D to A  from EEPROM
5675         // and read ThermalMeter from EEPROM
5676         //
5677         //if(!priv->AutoloadFailFlag)
5678         {
5679                 priv->EEPROMTxPowerDiff = *(u8 *)&hwinfo[EEPROM_PwDiff];
5680                 priv->EEPROMThermalMeter = *(u8 *)&hwinfo[EEPROM_ThermalMeter];
5681         }
5682         //else
5683         //{
5684         //      priv->EEPROMTxPowerDiff = EEPROM_Default_PwDiff;
5685         //      priv->EEPROMThermalMeter = EEPROM_Default_ThermalMeter;
5686         //}
5687
5688         RT_TRACE(COMP_INIT, "PwDiff = %#x\n", priv->EEPROMTxPowerDiff);
5689         RT_TRACE(COMP_INIT, "ThermalMeter = %#x\n", priv->EEPROMThermalMeter);
5690
5691         //
5692         // Read Tx Power gain offset of legacy OFDM to HT rate.
5693         // Read CrystalCap from EEPROM
5694         //
5695         //if(!priv->AutoloadFailFlag)
5696         {
5697                 priv->EEPROMCrystalCap = *(u8 *)&hwinfo[EEPROM_CrystalCap];
5698         }
5699         //else
5700         //{
5701         //      priv->EEPROMCrystalCap = EEPROM_Default_CrystalCap;
5702         //}
5703
5704         RT_TRACE(COMP_INIT, "CrystalCap = %#x\n", priv->EEPROMCrystalCap);
5705
5706         //
5707         // Get Tx Power Base.
5708         //
5709         //if(!priv->AutoloadFailFlag)
5710         {
5711                 priv->EEPROMTxPwrBase = *(u8 *)&hwinfo[EEPROM_TxPowerBase];
5712         }
5713         //else
5714         //{
5715         //      priv->EEPROMTxPwrBase = EEPROM_Default_TxPowerBase;
5716         //}
5717
5718         RT_TRACE(COMP_INIT, "TxPwrBase = %#x\n", priv->EEPROMTxPwrBase);
5719
5720
5721         //
5722         // Get TSSI value for each path.
5723         //
5724         //if(!priv->AutoloadFailFlag)
5725         {
5726                 priv->EEPROMTSSI_A = *(u8 *)&hwinfo[EEPROM_TSSI_A];
5727                 priv->EEPROMTSSI_B = *(u8 *)&hwinfo[EEPROM_TSSI_B];
5728         }
5729         //else
5730         //{ // Default setting for Empty EEPROM
5731         //      priv->EEPROMTSSI_A = EEPROM_Default_TSSI;
5732         //      priv->EEPROMTSSI_B = EEPROM_Default_TSSI;
5733         //}
5734
5735         RT_TRACE(COMP_INIT, "TSSI_A = %#x, TSSI_B = %#x\n", priv->EEPROMTSSI_A, priv->EEPROMTSSI_B);
5736
5737         //
5738         // Get Tx Power tracking mode.
5739         //
5740         //if(!priv->AutoloadFailFlag)
5741         {
5742                 priv->EEPROMTxPwrTkMode = *(u8 *)&hwinfo[EEPROM_TxPwTkMode];
5743         }
5744
5745         RT_TRACE(COMP_INIT, "TxPwrTkMod = %#x\n", priv->EEPROMTxPwrTkMode);
5746
5747
5748         {
5749                 //
5750                 // Buffer TxPwIdx(i.e., from offset 0x55~0x66, total 18Bytes)
5751                 // Update CCK, OFDM (1T/2T)Tx Power Index from above buffer.
5752                 //
5753
5754                 //
5755                 // Get Tx Power Level by Channel
5756                 //
5757                 //if(!priv->AutoloadFailFlag)
5758                 {
5759                         // Read Tx power of Channel 1 ~ 14 from EFUSE.
5760                         // 92S suupport RF A & B
5761                         for (rf_path = 0; rf_path < 2; rf_path++)
5762                         {
5763                                 for (i = 0; i < 3; i++)
5764                                 {
5765                                         // Read CCK RF A & B Tx power
5766                                         priv->RfCckChnlAreaTxPwr[rf_path][i] =
5767                                         hwinfo[EEPROM_TxPwIndex+rf_path*3+i];
5768
5769                                         // Read OFDM RF A & B Tx power for 1T
5770                                         priv->RfOfdmChnlAreaTxPwr1T[rf_path][i] =
5771                                         hwinfo[EEPROM_TxPwIndex+6+rf_path*3+i];
5772
5773                                         // Read OFDM RF A & B Tx power for 2T
5774                                         priv->RfOfdmChnlAreaTxPwr2T[rf_path][i] =
5775                                         hwinfo[EEPROM_TxPwIndex+12+rf_path*3+i];
5776                                 }
5777                         }
5778
5779                 }
5780 //
5781                 // Update Tx Power HAL variables.
5782 //
5783                 for (rf_path = 0; rf_path < 2; rf_path++)
5784                 {
5785                         for (i = 0; i < 3; i++)
5786                         {
5787                                 RT_TRACE((COMP_INIT),  "CCK RF-%d CHan_Area-%d = 0x%x\n",  rf_path, i,
5788                                 priv->RfCckChnlAreaTxPwr[rf_path][i]);
5789                                 RT_TRACE((COMP_INIT), "OFDM-1T RF-%d CHan_Area-%d = 0x%x\n",  rf_path, i,
5790                                 priv->RfOfdmChnlAreaTxPwr1T[rf_path][i]);
5791                                 RT_TRACE((COMP_INIT), "OFDM-2T RF-%d CHan_Area-%d = 0x%x\n",  rf_path, i, priv->RfOfdmChnlAreaTxPwr2T[rf_path][i]);
5792                         }
5793
5794                         // Assign dedicated channel tx power
5795                         for(i=0; i<14; i++)     // channel 1~3 use the same Tx Power Level.
5796                         {
5797                                 if (i < 3)                      // Cjanel 1-3
5798                                         index = 0;
5799                                 else if (i < 9)         // Channel 4-9
5800                                         index = 1;
5801                                 else                            // Channel 10-14
5802                                         index = 2;
5803
5804                                 // Record A & B CCK /OFDM - 1T/2T Channel area tx power
5805                                 priv->RfTxPwrLevelCck[rf_path][i]  =
5806                                 priv->RfCckChnlAreaTxPwr[rf_path][index];
5807                                 priv->RfTxPwrLevelOfdm1T[rf_path][i]  =
5808                                 priv->RfOfdmChnlAreaTxPwr1T[rf_path][index];
5809                                 priv->RfTxPwrLevelOfdm2T[rf_path][i]  =
5810                                 priv->RfOfdmChnlAreaTxPwr2T[rf_path][index];
5811                                 if (rf_path == 0)
5812                                 {
5813                                         priv->TxPowerLevelOFDM24G[i] = priv->RfTxPwrLevelOfdm1T[rf_path][i] ;
5814                                         priv->TxPowerLevelCCK[i] = priv->RfTxPwrLevelCck[rf_path][i];
5815                                 }
5816                         }
5817
5818                         for(i=0; i<14; i++)
5819                         {
5820                                 RT_TRACE((COMP_INIT),
5821                                 "Rf-%d TxPwr CH-%d CCK OFDM_1T OFDM_2T= 0x%x/0x%x/0x%x\n",
5822                                 rf_path, i, priv->RfTxPwrLevelCck[rf_path][i],
5823                                 priv->RfTxPwrLevelOfdm1T[rf_path][i] ,
5824                                 priv->RfTxPwrLevelOfdm2T[rf_path][i] );
5825                         }
5826                 }
5827         }
5828
5829         //
5830         // 2009/02/09 Cosa add for new EEPROM format
5831         //
5832         for(i=0; i<14; i++)     // channel 1~3 use the same Tx Power Level.
5833         {
5834                 // Read tx power difference between HT OFDM 20/40 MHZ
5835                 if (i < 3)                      // Cjanel 1-3
5836                         index = 0;
5837                 else if (i < 9)         // Channel 4-9
5838                         index = 1;
5839                 else                            // Channel 10-14
5840                         index = 2;
5841
5842                 tempval = (*(u8 *)&hwinfo[EEPROM_TX_PWR_HT20_DIFF+index])&0xff;
5843                 priv->TxPwrHt20Diff[RF90_PATH_A][i] = (tempval&0xF);
5844                 priv->TxPwrHt20Diff[RF90_PATH_B][i] = ((tempval>>4)&0xF);
5845
5846                 // Read OFDM<->HT tx power diff
5847                 if (i < 3)                      // Cjanel 1-3
5848                         tempval = (*(u8 *)&hwinfo[EEPROM_TX_PWR_OFDM_DIFF])&0xff;
5849                 else if (i < 9)         // Channel 4-9
5850                         tempval = (*(u8 *)&hwinfo[EEPROM_PwDiff])&0xff;
5851                 else                            // Channel 10-14
5852                         tempval = (*(u8 *)&hwinfo[EEPROM_TX_PWR_OFDM_DIFF+1])&0xff;
5853
5854                 //cosa tempval = (*(u1Byte *)&hwinfo[EEPROM_TX_PWR_OFDM_DIFF+index])&0xff;
5855                 priv->TxPwrLegacyHtDiff[RF90_PATH_A][i] = (tempval&0xF);
5856                 priv->TxPwrLegacyHtDiff[RF90_PATH_B][i] = ((tempval>>4)&0xF);
5857
5858                 //
5859                 // Read Band Edge tx power offset and check if user enable the ability
5860                 //
5861                 // HT 40 band edge channel
5862                 tempval = (*(u8 *)&hwinfo[EEPROM_TX_PWR_BAND_EDGE])&0xff;
5863                 priv->TxPwrbandEdgeHt40[RF90_PATH_A][0] = (tempval&0xF);                // Band edge low channel
5864                 priv->TxPwrbandEdgeHt40[RF90_PATH_A][1] =  ((tempval>>4)&0xF);  // Band edge high channel
5865                 tempval = (*(u8 *)&hwinfo[EEPROM_TX_PWR_BAND_EDGE+1])&0xff;
5866                 priv->TxPwrbandEdgeHt40[RF90_PATH_B][0] = (tempval&0xF);                // Band edge low channel
5867                 priv->TxPwrbandEdgeHt40[RF90_PATH_B][1] =  ((tempval>>4)&0xF);  // Band edge high channel
5868                 // HT 20 band edge channel
5869                 tempval = (*(u8 *)&hwinfo[EEPROM_TX_PWR_BAND_EDGE+2])&0xff;
5870                 priv->TxPwrbandEdgeHt20[RF90_PATH_A][0] = (tempval&0xF);                // Band edge low channel
5871                 priv->TxPwrbandEdgeHt20[RF90_PATH_A][1] =  ((tempval>>4)&0xF);  // Band edge high channel
5872                 tempval = (*(u8 *)&hwinfo[EEPROM_TX_PWR_BAND_EDGE+3])&0xff;
5873                 priv->TxPwrbandEdgeHt20[RF90_PATH_B][0] = (tempval&0xF);                // Band edge low channel
5874                 priv->TxPwrbandEdgeHt20[RF90_PATH_B][1] =  ((tempval>>4)&0xF);  // Band edge high channel
5875                 // OFDM band edge channel
5876                 tempval = (*(u8 *)&hwinfo[EEPROM_TX_PWR_BAND_EDGE+4])&0xff;
5877                 priv->TxPwrbandEdgeLegacyOfdm[RF90_PATH_A][0] = (tempval&0xF);          // Band edge low channel
5878                 priv->TxPwrbandEdgeLegacyOfdm[RF90_PATH_A][1] =  ((tempval>>4)&0xF);    // Band edge high channel
5879                 tempval = (*(u8 *)&hwinfo[EEPROM_TX_PWR_BAND_EDGE+5])&0xff;
5880                 priv->TxPwrbandEdgeLegacyOfdm[RF90_PATH_B][0] = (tempval&0xF);          // Band edge low channel
5881                 priv->TxPwrbandEdgeLegacyOfdm[RF90_PATH_B][1] =  ((tempval>>4)&0xF);    // Band edge high channel
5882
5883                 priv->TxPwrbandEdgeFlag = (*(u8 *)&hwinfo[TX_PWR_BAND_EDGE_CHK]);
5884         }
5885
5886         for(i=0; i<14; i++)
5887                 RT_TRACE(COMP_INIT, "RF-A Ht20 to HT40 Diff[%d] = 0x%x\n", i, priv->TxPwrHt20Diff[RF90_PATH_A][i]);
5888         for(i=0; i<14; i++)
5889                 RT_TRACE(COMP_INIT,  "RF-A Legacy to Ht40 Diff[%d] = 0x%x\n", i, priv->TxPwrLegacyHtDiff[RF90_PATH_A][i]);
5890         for(i=0; i<14; i++)
5891                 RT_TRACE(COMP_INIT,  "RF-B Ht20 to HT40 Diff[%d] = 0x%x\n", i, priv->TxPwrHt20Diff[RF90_PATH_B][i]);
5892         for(i=0; i<14; i++)
5893                 RT_TRACE(COMP_INIT,  "RF-B Legacy to HT40 Diff[%d] = 0x%x\n", i, priv->TxPwrLegacyHtDiff[RF90_PATH_B][i]);
5894         RT_TRACE(COMP_INIT, "RF-A HT40 band-edge low/high power diff = 0x%x/0x%x\n",
5895                 priv->TxPwrbandEdgeHt40[RF90_PATH_A][0],
5896                 priv->TxPwrbandEdgeHt40[RF90_PATH_A][1]);
5897         RT_TRACE((COMP_INIT&COMP_DBG), "RF-B HT40 band-edge low/high power diff = 0x%x/0x%x\n",
5898                 priv->TxPwrbandEdgeHt40[RF90_PATH_B][0],
5899                 priv->TxPwrbandEdgeHt40[RF90_PATH_B][1]);
5900
5901         RT_TRACE((COMP_INIT&COMP_DBG), "RF-A HT20 band-edge low/high power diff = 0x%x/0x%x\n",
5902                 priv->TxPwrbandEdgeHt20[RF90_PATH_A][0],
5903                 priv->TxPwrbandEdgeHt20[RF90_PATH_A][1]);
5904         RT_TRACE((COMP_INIT&COMP_DBG), "RF-B HT20 band-edge low/high power diff = 0x%x/0x%x\n",
5905                 priv->TxPwrbandEdgeHt20[RF90_PATH_B][0],
5906                 priv->TxPwrbandEdgeHt20[RF90_PATH_B][1]);
5907
5908         RT_TRACE((COMP_INIT&COMP_DBG), "RF-A OFDM band-edge low/high power diff = 0x%x/0x%x\n",
5909                 priv->TxPwrbandEdgeLegacyOfdm[RF90_PATH_A][0],
5910                 priv->TxPwrbandEdgeLegacyOfdm[RF90_PATH_A][1]);
5911         RT_TRACE((COMP_INIT&COMP_DBG), "RF-B OFDM band-edge low/high power diff = 0x%x/0x%x\n",
5912                 priv->TxPwrbandEdgeLegacyOfdm[RF90_PATH_B][0],
5913                 priv->TxPwrbandEdgeLegacyOfdm[RF90_PATH_B][1]);
5914         RT_TRACE((COMP_INIT&COMP_DBG), "Band-edge enable flag = %d\n", priv->TxPwrbandEdgeFlag);
5915
5916         //
5917         // Update remained HAL variables.
5918         //
5919         priv->TSSI_13dBm = priv->EEPROMThermalMeter *100;
5920         priv->LegacyHTTxPowerDiff = priv->EEPROMTxPowerDiff;
5921         priv->TxPowerDiff = priv->EEPROMTxPowerDiff;
5922         //priv->AntennaTxPwDiff[0] = (priv->EEPROMTxPowerDiff & 0xf);// Antenna B gain offset to antenna A, bit[3:0]
5923         //priv->AntennaTxPwDiff[1] = ((priv->EEPROMTxPowerDiff & 0xf0)>>4);// Antenna C gain offset to antenna A, bit[7:4]
5924         priv->CrystalCap = priv->EEPROMCrystalCap;      // CrystalCap, bit[15:12]
5925         priv->ThermalMeter[0] = (priv->EEPROMThermalMeter&0x1f);// ThermalMeter, bit0~3 for RFIC1, bit4~7 for RFIC2
5926         priv->LedStrategy = SW_LED_MODE0;
5927
5928         init_rate_adaptive(dev);
5929
5930         RT_TRACE(COMP_INIT, "<==== ReadAdapterInfo8192SUsb\n");
5931
5932         //return RT_STATUS_SUCCESS;
5933 }
5934
5935
5936 //
5937 //      Description:
5938 //              Read HW adapter information by E-Fuse or EEPROM according CR9346 reported.
5939 //
5940 //      Assumption:
5941 //              1. CR9346 regiser has verified.
5942 //              2. PASSIVE_LEVEL (USB interface)
5943 //
5944 //      Created by Roger, 2008.10.21.
5945 //
5946 static void rtl8192SU_read_eeprom_info(struct net_device *dev)
5947 {
5948         struct r8192_priv       *priv = ieee80211_priv(dev);
5949         u8                      tmpU1b;
5950
5951         RT_TRACE(COMP_INIT, "====> ReadAdapterInfo8192SUsb\n");
5952
5953         // Retrieve Chip version.
5954         priv->card_8192_version = (VERSION_8192S)((read_nic_dword(dev, PMC_FSM)>>16)&0xF);
5955         RT_TRACE(COMP_INIT, "Chip Version ID: 0x%2x\n", priv->card_8192_version);
5956
5957         tmpU1b = read_nic_byte(dev, EPROM_CMD);//CR9346
5958
5959         // To check system boot selection.
5960         if (tmpU1b & CmdEERPOMSEL)
5961         {
5962                 RT_TRACE(COMP_INIT, "Boot from EEPROM\n");
5963                 priv->EepromOrEfuse = TRUE;
5964         }
5965         else
5966         {
5967                 RT_TRACE(COMP_INIT, "Boot from EFUSE\n");
5968                 priv->EepromOrEfuse = FALSE;
5969         }
5970
5971         // To check autoload success or not.
5972         if (tmpU1b & CmdEEPROM_En)
5973         {
5974                 RT_TRACE(COMP_INIT, "Autoload OK!!\n");
5975                 priv->AutoloadFailFlag=FALSE;
5976                 rtl8192SU_ReadAdapterInfo8192SUsb(dev);//eeprom or e-fuse
5977         }
5978         else
5979         { // Auto load fail.
5980                 RT_TRACE(COMP_INIT, "AutoLoad Fail reported from CR9346!!\n");
5981                 priv->AutoloadFailFlag=TRUE;
5982                 rtl8192SU_ConfigAdapterInfo8192SForAutoLoadFail(dev);
5983
5984                 //if (IS_BOOT_FROM_EFUSE(Adapter))
5985                 if(!priv->EepromOrEfuse)
5986                 {
5987                         RT_TRACE(COMP_INIT, "Update shadow map for EFuse future use!!\n");
5988                         EFUSE_ShadowMapUpdate(dev);
5989                 }
5990         }
5991 #ifdef TO_DO_LIST
5992         if((priv->RegChannelPlan >= RT_CHANNEL_DOMAIN_MAX) || (pHalData->EEPROMChannelPlan & EEPROM_CHANNEL_PLAN_BY_HW_MASK))
5993         {
5994                 pMgntInfo->ChannelPlan = HalMapChannelPlan8192S(Adapter, (pHalData->EEPROMChannelPlan & (~(EEPROM_CHANNEL_PLAN_BY_HW_MASK))));
5995                 pMgntInfo->bChnlPlanFromHW = (pHalData->EEPROMChannelPlan & EEPROM_CHANNEL_PLAN_BY_HW_MASK) ? TRUE : FALSE; // User cannot change  channel plan.
5996         }
5997         else
5998         {
5999                 pMgntInfo->ChannelPlan = (RT_CHANNEL_DOMAIN)pMgntInfo->RegChannelPlan;
6000         }
6001
6002         switch(pMgntInfo->ChannelPlan)
6003         {
6004                 case RT_CHANNEL_DOMAIN_GLOBAL_DOAMIN:
6005                 {
6006                         PRT_DOT11D_INFO pDot11dInfo = GET_DOT11D_INFO(pMgntInfo);
6007
6008                         pDot11dInfo->bEnabled = TRUE;
6009                 }
6010                 RT_TRACE(COMP_INIT, DBG_LOUD, ("ReadAdapterInfo8187(): Enable dot11d when RT_CHANNEL_DOMAIN_GLOBAL_DOAMIN!\n"));
6011                 break;
6012         }
6013
6014         RT_TRACE(COMP_INIT, DBG_LOUD, ("RegChannelPlan(%d) EEPROMChannelPlan(%d)", pMgntInfo->RegChannelPlan, pHalData->EEPROMChannelPlan));
6015         RT_TRACE(COMP_INIT, DBG_LOUD, ("ChannelPlan = %d\n" , pMgntInfo->ChannelPlan));
6016
6017         RT_TRACE(COMP_INIT, DBG_LOUD, ("<==== ReadAdapterInfo8192S\n"));
6018 #endif
6019
6020         RT_TRACE(COMP_INIT, "<==== ReadAdapterInfo8192SUsb\n");
6021
6022         //return RT_STATUS_SUCCESS;
6023 }
6024 #else
6025 static void rtl8192_read_eeprom_info(struct net_device* dev)
6026 {
6027         u16 wEPROM_ID = 0;
6028         u8 bMac_Tmp_Addr[6] = {0x00, 0xe0, 0x4c, 0x00, 0x00, 0x02};
6029         u8 bLoad_From_EEPOM = false;
6030         struct r8192_priv *priv = ieee80211_priv(dev);
6031         u16 tmpValue = 0;
6032         RT_TRACE(COMP_EPROM, "===========>%s()\n", __FUNCTION__);
6033         wEPROM_ID = eprom_read(dev, 0); //first read EEPROM ID out;
6034         RT_TRACE(COMP_EPROM, "EEPROM ID is 0x%x\n", wEPROM_ID);
6035
6036         if (wEPROM_ID != RTL8190_EEPROM_ID)
6037         {
6038                 RT_TRACE(COMP_ERR, "EEPROM ID is invalid(is 0x%x(should be 0x%x)\n", wEPROM_ID, RTL8190_EEPROM_ID);
6039         }
6040         else
6041                 bLoad_From_EEPOM = true;
6042
6043         if (bLoad_From_EEPOM)
6044         {
6045                 tmpValue = eprom_read(dev, (EEPROM_VID>>1));
6046                 priv->eeprom_vid = endian_swap(&tmpValue);
6047                 priv->eeprom_pid = eprom_read(dev, (EEPROM_PID>>1));
6048                 tmpValue = eprom_read(dev, (EEPROM_ChannelPlan>>1));
6049                 priv->eeprom_ChannelPlan =((tmpValue&0xff00)>>8);
6050                 priv->btxpowerdata_readfromEEPORM = true;
6051                 priv->eeprom_CustomerID = eprom_read(dev, (EEPROM_Customer_ID>>1)) >>8;
6052         }
6053         else
6054         {
6055                 priv->eeprom_vid = 0;
6056                 priv->eeprom_pid = 0;
6057                 priv->card_8192_version = VERSION_819xU_B;
6058                 priv->eeprom_ChannelPlan = 0;
6059                 priv->eeprom_CustomerID = 0;
6060         }
6061         RT_TRACE(COMP_EPROM, "vid:0x%4x, pid:0x%4x, CustomID:0x%2x, ChanPlan:0x%x\n", priv->eeprom_vid, priv->eeprom_pid, priv->eeprom_CustomerID, priv->eeprom_ChannelPlan);
6062         //set channelplan from eeprom
6063         priv->ChannelPlan = priv->eeprom_ChannelPlan;
6064         if (bLoad_From_EEPOM)
6065         {
6066                 int i;
6067                 for (i=0; i<6; i+=2)
6068                 {
6069                         u16 tmp = 0;
6070                         tmp = eprom_read(dev, (u16)((EEPROM_NODE_ADDRESS_BYTE_0 + i)>>1));
6071                         *(u16*)(&dev->dev_addr[i]) = tmp;
6072                 }
6073         }
6074         else
6075         {
6076                 memcpy(dev->dev_addr, bMac_Tmp_Addr, 6);
6077                 //should I set IDR0 here?
6078         }
6079         RT_TRACE(COMP_EPROM, "MAC addr:"MAC_FMT"\n", MAC_ARG(dev->dev_addr));
6080         priv->rf_type = RTL819X_DEFAULT_RF_TYPE; //default 1T2R
6081         priv->rf_chip = RF_8256;
6082
6083         if (priv->card_8192_version == (u8)VERSION_819xU_A)
6084         {
6085                 //read Tx power gain offset of legacy OFDM to HT rate
6086                 if (bLoad_From_EEPOM)
6087                         priv->EEPROMTxPowerDiff = (eprom_read(dev, (EEPROM_TxPowerDiff>>1))&0xff00) >> 8;
6088                 else
6089                         priv->EEPROMTxPowerDiff = EEPROM_Default_TxPower;
6090                 RT_TRACE(COMP_EPROM, "TxPowerDiff:%d\n", priv->EEPROMTxPowerDiff);
6091                 //read ThermalMeter from EEPROM
6092                 if (bLoad_From_EEPOM)
6093                         priv->EEPROMThermalMeter = (u8)(eprom_read(dev, (EEPROM_ThermalMeter>>1))&0x00ff);
6094                 else
6095                         priv->EEPROMThermalMeter = EEPROM_Default_ThermalMeter;
6096                 RT_TRACE(COMP_EPROM, "ThermalMeter:%d\n", priv->EEPROMThermalMeter);
6097                 //vivi, for tx power track
6098                 priv->TSSI_13dBm = priv->EEPROMThermalMeter *100;
6099                 //read antenna tx power offset of B/C/D to A from EEPROM
6100                 if (bLoad_From_EEPOM)
6101                         priv->EEPROMPwDiff = (eprom_read(dev, (EEPROM_PwDiff>>1))&0x0f00)>>8;
6102                 else
6103                         priv->EEPROMPwDiff = EEPROM_Default_PwDiff;
6104                 RT_TRACE(COMP_EPROM, "TxPwDiff:%d\n", priv->EEPROMPwDiff);
6105                 // Read CrystalCap from EEPROM
6106                 if (bLoad_From_EEPOM)
6107                         priv->EEPROMCrystalCap = (eprom_read(dev, (EEPROM_CrystalCap>>1))&0x0f);
6108                 else
6109                         priv->EEPROMCrystalCap = EEPROM_Default_CrystalCap;
6110                 RT_TRACE(COMP_EPROM, "CrystalCap = %d\n", priv->EEPROMCrystalCap);
6111                 //get per-channel Tx power level
6112                 if (bLoad_From_EEPOM)
6113                         priv->EEPROM_Def_Ver = (eprom_read(dev, (EEPROM_TxPwIndex_Ver>>1))&0xff00)>>8;
6114                 else
6115                         priv->EEPROM_Def_Ver = 1;
6116                 RT_TRACE(COMP_EPROM, "EEPROM_DEF_VER:%d\n", priv->EEPROM_Def_Ver);
6117                 if (priv->EEPROM_Def_Ver == 0) //old eeprom definition
6118                 {
6119                         int i;
6120                         if (bLoad_From_EEPOM)
6121                                 priv->EEPROMTxPowerLevelCCK = (eprom_read(dev, (EEPROM_TxPwIndex_CCK>>1))&0xff) >> 8;
6122                         else
6123                                 priv->EEPROMTxPowerLevelCCK = 0x10;
6124                         RT_TRACE(COMP_EPROM, "CCK Tx Power Levl: 0x%02x\n", priv->EEPROMTxPowerLevelCCK);
6125                         for (i=0; i<3; i++)
6126                         {
6127                                 if (bLoad_From_EEPOM)
6128                                 {
6129                                         tmpValue = eprom_read(dev, (EEPROM_TxPwIndex_OFDM_24G+i)>>1);
6130                                         if (((EEPROM_TxPwIndex_OFDM_24G+i) % 2) == 0)
6131                                                 tmpValue = tmpValue & 0x00ff;
6132                                         else
6133                                                 tmpValue = (tmpValue & 0xff00) >> 8;
6134                                 }
6135                                 else
6136                                         tmpValue = 0x10;
6137                                 priv->EEPROMTxPowerLevelOFDM24G[i] = (u8) tmpValue;
6138                                 RT_TRACE(COMP_EPROM, "OFDM 2.4G Tx Power Level, Index %d = 0x%02x\n", i, priv->EEPROMTxPowerLevelCCK);
6139                         }
6140                 }//end if EEPROM_DEF_VER == 0
6141                 else if (priv->EEPROM_Def_Ver == 1)
6142                 {
6143                         if (bLoad_From_EEPOM)
6144                         {
6145                                 tmpValue = eprom_read(dev, (EEPROM_TxPwIndex_CCK_V1>>1));
6146                                 tmpValue = (tmpValue & 0xff00) >> 8;
6147                         }
6148                         else
6149                                 tmpValue = 0x10;
6150                         priv->EEPROMTxPowerLevelCCK_V1[0] = (u8)tmpValue;
6151
6152                         if (bLoad_From_EEPOM)
6153                                 tmpValue = eprom_read(dev, (EEPROM_TxPwIndex_CCK_V1 + 2)>>1);
6154                         else
6155                                 tmpValue = 0x1010;
6156                         *((u16*)(&priv->EEPROMTxPowerLevelCCK_V1[1])) = tmpValue;
6157                         if (bLoad_From_EEPOM)
6158                                 tmpValue = eprom_read(dev, (EEPROM_TxPwIndex_OFDM_24G_V1>>1));
6159                         else
6160                                 tmpValue = 0x1010;
6161                         *((u16*)(&priv->EEPROMTxPowerLevelOFDM24G[0])) = tmpValue;
6162                         if (bLoad_From_EEPOM)
6163                                 tmpValue = eprom_read(dev, (EEPROM_TxPwIndex_OFDM_24G_V1+2)>>1);
6164                         else
6165                                 tmpValue = 0x10;
6166                         priv->EEPROMTxPowerLevelOFDM24G[2] = (u8)tmpValue;
6167                 }//endif EEPROM_Def_Ver == 1
6168
6169                 //update HAL variables
6170                 //
6171                 {
6172                         int i;
6173                         for (i=0; i<14; i++)
6174                         {
6175                                 if (i<=3)
6176                                         priv->TxPowerLevelOFDM24G[i] = priv->EEPROMTxPowerLevelOFDM24G[0];
6177                                 else if (i>=4 && i<=9)
6178                                         priv->TxPowerLevelOFDM24G[i] = priv->EEPROMTxPowerLevelOFDM24G[1];
6179                                 else
6180                                         priv->TxPowerLevelOFDM24G[i] = priv->EEPROMTxPowerLevelOFDM24G[2];
6181                         }
6182
6183                         for (i=0; i<14; i++)
6184                         {
6185                                 if (priv->EEPROM_Def_Ver == 0)
6186                                 {
6187                                         if (i<=3)
6188                                                 priv->TxPowerLevelCCK[i] = priv->EEPROMTxPowerLevelOFDM24G[0] + (priv->EEPROMTxPowerLevelCCK - priv->EEPROMTxPowerLevelOFDM24G[1]);
6189                                         else if (i>=4 && i<=9)
6190                                                 priv->TxPowerLevelCCK[i] = priv->EEPROMTxPowerLevelCCK;
6191                                         else
6192                                                 priv->TxPowerLevelCCK[i] = priv->EEPROMTxPowerLevelOFDM24G[2] + (priv->EEPROMTxPowerLevelCCK - priv->EEPROMTxPowerLevelOFDM24G[1]);
6193                                 }
6194                                 else if (priv->EEPROM_Def_Ver == 1)
6195                                 {
6196                                         if (i<=3)
6197                                                 priv->TxPowerLevelCCK[i] = priv->EEPROMTxPowerLevelCCK_V1[0];
6198                                         else if (i>=4 && i<=9)
6199                                                 priv->TxPowerLevelCCK[i] = priv->EEPROMTxPowerLevelCCK_V1[1];
6200                                         else
6201                                                 priv->TxPowerLevelCCK[i] = priv->EEPROMTxPowerLevelCCK_V1[2];
6202                                 }
6203                         }
6204                 }//end update HAL variables
6205                 priv->TxPowerDiff = priv->EEPROMPwDiff;
6206 // Antenna B gain offset to antenna A, bit0~3
6207                 priv->AntennaTxPwDiff[0] = (priv->EEPROMTxPowerDiff & 0xf);
6208                 // Antenna C gain offset to antenna A, bit4~7
6209                 priv->AntennaTxPwDiff[1] = ((priv->EEPROMTxPowerDiff & 0xf0)>>4);
6210                 // CrystalCap, bit12~15
6211                 priv->CrystalCap = priv->EEPROMCrystalCap;
6212                 // ThermalMeter, bit0~3 for RFIC1, bit4~7 for RFIC2
6213                 // 92U does not enable TX power tracking.
6214                 priv->ThermalMeter[0] = priv->EEPROMThermalMeter;
6215         }//end if VersionID == VERSION_819xU_A
6216
6217 //added by vivi, for dlink led, 20080416
6218         switch(priv->eeprom_CustomerID)
6219         {
6220                 case EEPROM_CID_RUNTOP:
6221                         priv->CustomerID = RT_CID_819x_RUNTOP;
6222                         break;
6223
6224                 case EEPROM_CID_DLINK:
6225                         priv->CustomerID = RT_CID_DLINK;
6226                         break;
6227
6228                 default:
6229                         priv->CustomerID = RT_CID_DEFAULT;
6230                         break;
6231
6232         }
6233
6234         switch(priv->CustomerID)
6235         {
6236                 case RT_CID_819x_RUNTOP:
6237                         priv->LedStrategy = SW_LED_MODE2;
6238                         break;
6239
6240                 case RT_CID_DLINK:
6241                         priv->LedStrategy = SW_LED_MODE4;
6242                         break;
6243
6244                 default:
6245                         priv->LedStrategy = SW_LED_MODE0;
6246                         break;
6247
6248         }
6249
6250
6251         if(priv->rf_type == RF_1T2R)
6252         {
6253                 RT_TRACE(COMP_EPROM, "\n1T2R config\n");
6254         }
6255         else
6256         {
6257                 RT_TRACE(COMP_EPROM, "\n2T4R config\n");
6258         }
6259
6260         // 2008/01/16 MH We can only know RF type in the function. So we have to init
6261         // DIG RATR table again.
6262         init_rate_adaptive(dev);
6263         //we need init DIG RATR table here again.
6264
6265         RT_TRACE(COMP_EPROM, "<===========%s()\n", __FUNCTION__);
6266         return;
6267 }
6268 #endif
6269
6270 short rtl8192_get_channel_map(struct net_device * dev)
6271 {
6272         struct r8192_priv *priv = ieee80211_priv(dev);
6273         if(priv->ChannelPlan > COUNTRY_CODE_GLOBAL_DOMAIN){
6274                 printk("rtl8180_init:Error channel plan! Set to default.\n");
6275                 priv->ChannelPlan= 0;
6276         }
6277         RT_TRACE(COMP_INIT, "Channel plan is %d\n",priv->ChannelPlan);
6278
6279         rtl819x_set_channel_map(priv->ChannelPlan, priv);
6280         return 0;
6281 }
6282
6283 short rtl8192_init(struct net_device *dev)
6284 {
6285
6286         struct r8192_priv *priv = ieee80211_priv(dev);
6287
6288 #ifndef RTL8192SU
6289         memset(&(priv->stats),0,sizeof(struct Stats));
6290         memset(priv->txqueue_to_outpipemap,0,9);
6291 #ifdef PIPE12
6292         {
6293                 int i=0;
6294                 u8 queuetopipe[]={3,2,1,0,4,8,7,6,5};
6295                 memcpy(priv->txqueue_to_outpipemap,queuetopipe,9);
6296 /*              for(i=0;i<9;i++)
6297                         printk("%d ",priv->txqueue_to_outpipemap[i]);
6298                 printk("\n");*/
6299         }
6300 #else
6301         {
6302                 u8 queuetopipe[]={3,2,1,0,4,4,0,4,4};
6303                 memcpy(priv->txqueue_to_outpipemap,queuetopipe,9);
6304 /*              for(i=0;i<9;i++)
6305                         printk("%d ",priv->txqueue_to_outpipemap[i]);
6306                 printk("\n");*/
6307         }
6308 #endif
6309 #endif
6310         rtl8192_init_priv_variable(dev);
6311         rtl8192_init_priv_lock(priv);
6312         rtl8192_init_priv_task(dev);
6313         rtl8192_get_eeprom_size(dev);
6314         priv->ops->rtl819x_read_eeprom_info(dev);
6315         rtl8192_get_channel_map(dev);
6316         init_hal_dm(dev);
6317         init_timer(&priv->watch_dog_timer);
6318         priv->watch_dog_timer.data = (unsigned long)dev;
6319         priv->watch_dog_timer.function = watch_dog_timer_callback;
6320
6321         //rtl8192_adapter_start(dev);
6322 #ifdef DEBUG_EPROM
6323         dump_eprom(dev);
6324 #endif
6325         return 0;
6326 }
6327
6328 /******************************************************************************
6329  *function:  This function actually only set RRSR, RATR and BW_OPMODE registers
6330  *           not to do all the hw config as its name says
6331  *   input:  net_device dev
6332  *  output:  none
6333  *  return:  none
6334  *  notice:  This part need to modified according to the rate set we filtered
6335  * ****************************************************************************/
6336 void rtl8192_hwconfig(struct net_device* dev)
6337 {
6338         u32 regRATR = 0, regRRSR = 0;
6339         u8 regBwOpMode = 0, regTmp = 0;
6340         struct r8192_priv *priv = ieee80211_priv(dev);
6341
6342 // Set RRSR, RATR, and BW_OPMODE registers
6343         //
6344         switch(priv->ieee80211->mode)
6345         {
6346         case WIRELESS_MODE_B:
6347                 regBwOpMode = BW_OPMODE_20MHZ;
6348                 regRATR = RATE_ALL_CCK;
6349                 regRRSR = RATE_ALL_CCK;
6350                 break;
6351         case WIRELESS_MODE_A:
6352                 regBwOpMode = BW_OPMODE_5G |BW_OPMODE_20MHZ;
6353                 regRATR = RATE_ALL_OFDM_AG;
6354                 regRRSR = RATE_ALL_OFDM_AG;
6355                 break;
6356         case WIRELESS_MODE_G:
6357                 regBwOpMode = BW_OPMODE_20MHZ;
6358                 regRATR = RATE_ALL_CCK | RATE_ALL_OFDM_AG;
6359                 regRRSR = RATE_ALL_CCK | RATE_ALL_OFDM_AG;
6360                 break;
6361         case WIRELESS_MODE_AUTO:
6362 #ifdef TO_DO_LIST
6363                 if (Adapter->bInHctTest)
6364                 {
6365                     regBwOpMode = BW_OPMODE_20MHZ;
6366                     regRATR = RATE_ALL_CCK | RATE_ALL_OFDM_AG;
6367                     regRRSR = RATE_ALL_CCK | RATE_ALL_OFDM_AG;
6368                 }
6369                 else
6370 #endif
6371                 {
6372                     regBwOpMode = BW_OPMODE_20MHZ;
6373                     regRATR = RATE_ALL_CCK | RATE_ALL_OFDM_AG | RATE_ALL_OFDM_1SS | RATE_ALL_OFDM_2SS;
6374                     regRRSR = RATE_ALL_CCK | RATE_ALL_OFDM_AG;
6375                 }
6376                 break;
6377         case WIRELESS_MODE_N_24G:
6378                 // It support CCK rate by default.
6379                 // CCK rate will be filtered out only when associated AP does not support it.
6380                 regBwOpMode = BW_OPMODE_20MHZ;
6381                         regRATR = RATE_ALL_CCK | RATE_ALL_OFDM_AG | RATE_ALL_OFDM_1SS | RATE_ALL_OFDM_2SS;
6382                         regRRSR = RATE_ALL_CCK | RATE_ALL_OFDM_AG;
6383                 break;
6384         case WIRELESS_MODE_N_5G:
6385                 regBwOpMode = BW_OPMODE_5G;
6386                 regRATR = RATE_ALL_OFDM_AG | RATE_ALL_OFDM_1SS | RATE_ALL_OFDM_2SS;
6387                 regRRSR = RATE_ALL_OFDM_AG;
6388                 break;
6389         }
6390
6391         write_nic_byte(dev, BW_OPMODE, regBwOpMode);
6392         {
6393                 u32 ratr_value = 0;
6394                 ratr_value = regRATR;
6395                 if (priv->rf_type == RF_1T2R)
6396                 {
6397                         ratr_value &= ~(RATE_ALL_OFDM_2SS);
6398                 }
6399                 write_nic_dword(dev, RATR0, ratr_value);
6400                 write_nic_byte(dev, UFWP, 1);
6401         }
6402         regTmp = read_nic_byte(dev, 0x313);
6403         regRRSR = ((regTmp) << 24) | (regRRSR & 0x00ffffff);
6404         write_nic_dword(dev, RRSR, regRRSR);
6405
6406         //
6407         // Set Retry Limit here
6408         //
6409         write_nic_word(dev, RETRY_LIMIT,
6410                         priv->ShortRetryLimit << RETRY_LIMIT_SHORT_SHIFT | \
6411                         priv->LongRetryLimit << RETRY_LIMIT_LONG_SHIFT);
6412         // Set Contention Window here
6413
6414         // Set Tx AGC
6415
6416         // Set Tx Antenna including Feedback control
6417
6418         // Set Auto Rate fallback control
6419
6420
6421 }
6422
6423 #ifdef RTL8192SU
6424
6425 //
6426 //      Description:
6427 //              Initial HW relted registers.
6428 //
6429 //      Assumption:
6430 //              Config RTL8192S USB MAC, we should config MAC before download FW.
6431 //
6432 //      2008.09.03, Added by Roger.
6433 //
6434 static void rtl8192SU_MacConfigBeforeFwDownloadASIC(struct net_device *dev)
6435 {
6436         u8                              tmpU1b;// i;
6437 //      u16                             tmpU2b;
6438 //      u32                             tmpU4b;
6439         u8                              PollingCnt = 20;
6440
6441         RT_TRACE(COMP_INIT, "--->MacConfigBeforeFwDownloadASIC()\n");
6442
6443         //2MAC Initialization for power on sequence, Revised by Roger. 2008.09.03.
6444
6445         //
6446         //<Roger_Notes> Set control path switch to HW control and reset Digital Core,  CPU Core and
6447         // MAC I/O to solve FW download fail when system from resume sate.
6448         // 2008.11.04.
6449         //
6450        tmpU1b = read_nic_byte(dev, SYS_CLKR+1);
6451        if(tmpU1b & 0x80)
6452         {
6453         tmpU1b &= 0x3f;
6454               write_nic_byte(dev, SYS_CLKR+1, tmpU1b);
6455        }
6456         // Clear FW RPWM for FW control LPS. by tynli. 2009.02.23
6457         write_nic_byte(dev, RPWM, 0x0);
6458
6459        tmpU1b = read_nic_byte(dev, SYS_FUNC_EN+1);
6460        tmpU1b &= 0x73;
6461        write_nic_byte(dev, SYS_FUNC_EN+1, tmpU1b);
6462        udelay(1000);
6463
6464         //Revised POS, suggested by SD1 Alex, 2008.09.27.
6465         write_nic_byte(dev, SPS0_CTRL+1, 0x53);
6466         write_nic_byte(dev, SPS0_CTRL, 0x57);
6467
6468         //Enable AFE Macro Block's Bandgap adn Enable AFE Macro Block's Mbias
6469         tmpU1b = read_nic_byte(dev, AFE_MISC);
6470         write_nic_byte(dev, AFE_MISC, (tmpU1b|AFE_BGEN|AFE_MBEN));
6471
6472         //Enable PLL Power (LDOA15V)
6473         tmpU1b = read_nic_byte(dev, LDOA15_CTRL);
6474         write_nic_byte(dev, LDOA15_CTRL, (tmpU1b|LDA15_EN));
6475
6476         //Enable LDOV12D block
6477         tmpU1b = read_nic_byte(dev, LDOV12D_CTRL);
6478         write_nic_byte(dev, LDOV12D_CTRL, (tmpU1b|LDV12_EN));
6479
6480         //mpU1b = read_nic_byte(Adapter, SPS1_CTRL);
6481         //write_nic_byte(dev, SPS1_CTRL, (tmpU1b|SPS1_LDEN));
6482
6483         //PlatformSleepUs(2000);
6484
6485         //Enable Switch Regulator Block
6486         //tmpU1b = read_nic_byte(Adapter, SPS1_CTRL);
6487         //write_nic_byte(dev, SPS1_CTRL, (tmpU1b|SPS1_SWEN));
6488
6489         //write_nic_dword(Adapter, SPS1_CTRL, 0x00a7b267);
6490
6491         tmpU1b = read_nic_byte(dev, SYS_ISO_CTRL+1);
6492         write_nic_byte(dev, SYS_ISO_CTRL+1, (tmpU1b|0x08));
6493
6494         //Engineer Packet CP test Enable
6495         tmpU1b = read_nic_byte(dev, SYS_FUNC_EN+1);
6496         write_nic_byte(dev, SYS_FUNC_EN+1, (tmpU1b|0x20));
6497
6498         //Support 64k IMEM, suggested by SD1 Alex.
6499         tmpU1b = read_nic_byte(dev, SYS_ISO_CTRL+1);
6500         write_nic_byte(dev, SYS_ISO_CTRL+1, (tmpU1b& 0x68));
6501
6502         //Enable AFE clock
6503         tmpU1b = read_nic_byte(dev, AFE_XTAL_CTRL+1);
6504         write_nic_byte(dev, AFE_XTAL_CTRL+1, (tmpU1b& 0xfb));
6505
6506         //Enable AFE PLL Macro Block
6507         tmpU1b = read_nic_byte(dev, AFE_PLL_CTRL);
6508         write_nic_byte(dev, AFE_PLL_CTRL, (tmpU1b|0x11));
6509
6510         //Attatch AFE PLL to MACTOP/BB/PCIe Digital
6511         tmpU1b = read_nic_byte(dev, SYS_ISO_CTRL);
6512         write_nic_byte(dev, SYS_ISO_CTRL, (tmpU1b&0xEE));
6513
6514         // Switch to 40M clock
6515         write_nic_byte(dev, SYS_CLKR, 0x00);
6516
6517         //SSC Disable
6518         tmpU1b = read_nic_byte(dev, SYS_CLKR);
6519         //write_nic_byte(dev, SYS_CLKR, (tmpU1b&0x5f));
6520         write_nic_byte(dev, SYS_CLKR, (tmpU1b|0xa0));
6521
6522         //Enable MAC clock
6523         tmpU1b = read_nic_byte(dev, SYS_CLKR+1);
6524         write_nic_byte(dev, SYS_CLKR+1, (tmpU1b|0x18));
6525
6526         //Revised POS, suggested by SD1 Alex, 2008.09.27.
6527         write_nic_byte(dev, PMC_FSM, 0x02);
6528
6529         //Enable Core digital and enable IOREG R/W
6530         tmpU1b = read_nic_byte(dev, SYS_FUNC_EN+1);
6531         write_nic_byte(dev, SYS_FUNC_EN+1, (tmpU1b|0x08));
6532
6533         //Enable REG_EN
6534         tmpU1b = read_nic_byte(dev, SYS_FUNC_EN+1);
6535         write_nic_byte(dev, SYS_FUNC_EN+1, (tmpU1b|0x80));
6536
6537         //Switch the control path to FW
6538         tmpU1b = read_nic_byte(dev, SYS_CLKR+1);
6539         write_nic_byte(dev, SYS_CLKR+1, (tmpU1b|0x80)& 0xBF);
6540
6541         write_nic_byte(dev, CMDR, 0xFC);
6542         write_nic_byte(dev, CMDR+1, 0x37);
6543
6544         //Fix the RX FIFO issue(usb error), 970410
6545         tmpU1b = read_nic_byte_E(dev, 0x5c);
6546         write_nic_byte_E(dev, 0x5c, (tmpU1b|BIT7));
6547
6548          //For power save, used this in the bit file after 970621
6549         tmpU1b = read_nic_byte(dev, SYS_CLKR);
6550         write_nic_byte(dev, SYS_CLKR, tmpU1b&(~SYS_CPU_CLKSEL));
6551
6552         // Revised for 8051 ROM code wrong operation. Added by Roger. 2008.10.16.
6553         write_nic_byte_E(dev, 0x1c, 0x80);
6554
6555         //
6556         // <Roger_EXP> To make sure that TxDMA can ready to download FW.
6557         // We should reset TxDMA if IMEM RPT was not ready.
6558         // Suggested by SD1 Alex. 2008.10.23.
6559         //
6560         do
6561         {
6562                 tmpU1b = read_nic_byte(dev, TCR);
6563                 if((tmpU1b & TXDMA_INIT_VALUE) == TXDMA_INIT_VALUE)
6564                         break;
6565                 //PlatformStallExecution(5);
6566                 udelay(5);
6567         }while(PollingCnt--);   // Delay 1ms
6568
6569         if(PollingCnt <= 0 )
6570         {
6571                 RT_TRACE(COMP_INIT, "MacConfigBeforeFwDownloadASIC(): Polling TXDMA_INIT_VALUE timeout!! Current TCR(%#x)\n", tmpU1b);
6572                 tmpU1b = read_nic_byte(dev, CMDR);
6573                 write_nic_byte(dev, CMDR, tmpU1b&(~TXDMA_EN));
6574                 udelay(2);
6575                 write_nic_byte(dev, CMDR, tmpU1b|TXDMA_EN);// Reset TxDMA
6576         }
6577
6578
6579         RT_TRACE(COMP_INIT, "<---MacConfigBeforeFwDownloadASIC()\n");
6580 }
6581
6582
6583 #if 0
6584 static void rtl8192SU_SetHwRegAmpduMinSpace(struct net_device *dev, u8 MinSpaceCfg)
6585 {
6586         struct r8192_priv *priv = ieee80211_priv((struct net_device *)dev);
6587         struct ieee80211_device* ieee = priv->ieee80211;
6588         u8      MinSpacingToSet;
6589         u8      SecMinSpace;
6590
6591 #ifdef RTL8192S_PREPARE_FOR_NORMAL_RELEASE
6592         MinSpacingToSet = MinSpaceCfg;
6593         if(MinSpacingToSet <= 7)
6594         {
6595                 switch(ieee->pairwise_key_type)
6596                 {
6597                         case    KEY_TYPE_NA:                    SecMinSpace = 0;                break;
6598                         case    KEY_TYPE_CCMP:
6599                         case    KEY_TYPE_WEP40:
6600                         case    KEY_TYPE_WEP104:
6601                         case    KEY_TYPE_TKIP:          SecMinSpace = 6;                break;
6602                         default:                                        SecMinSpace = 7;                break;
6603                 }
6604
6605                 if(MinSpacingToSet < SecMinSpace)
6606                         MinSpacingToSet = SecMinSpace;
6607                 priv->MinSpaceCfg = ((priv->MinSpaceCfg&0xf8) |MinSpacingToSet);
6608                 RT_TRACE(COMP_SEC, "Set AMPDU_MIN_SPACE: %x\n", priv->MinSpaceCfg);
6609                 write_nic_byte(dev, AMPDU_MIN_SPACE, priv->MinSpaceCfg);
6610         }
6611
6612 #else
6613         MinSpacingToSet = MinSpaceCfg;
6614         MinSpacingToSet &= 0x07; // We only care about bit[2:0]
6615         priv->MinSpaceCfg |= MinSpacingToSet;
6616         RT_TRACE(COMP_SEC, "Set AMPDU_MIN_SPACE: %x\n", priv->MinSpaceCfg);
6617         write_nic_byte(dev, AMPDU_MIN_SPACE, priv->MinSpaceCfg);//FIXLZM
6618 #endif
6619 }
6620 #endif
6621
6622 //
6623 //      Description:
6624 //              Initial HW relted registers.
6625 //
6626 //      Assumption:
6627 //              1. This function is only invoked at driver intialization once.
6628 //              2. PASSIVE LEVEL.
6629 //
6630 //      2008.06.10, Added by Roger.
6631 //
6632 static void rtl8192SU_MacConfigAfterFwDownload(struct net_device *dev)
6633 {
6634         struct r8192_priv *priv = ieee80211_priv((struct net_device *)dev);
6635         //PRT_HIGH_THROUGHPUT   pHTInfo = priv->ieee80211->pHTInfo;
6636         //u8    tmpU1b, RxPageCfg, i;
6637         u16     tmpU2b;
6638         u8      tmpU1b;//, i;
6639
6640
6641         RT_TRACE(COMP_INIT, "--->MacConfigAfterFwDownload()\n");
6642
6643         // Enable Tx/Rx
6644         tmpU2b = (BBRSTn|BB_GLB_RSTn|SCHEDULE_EN|MACRXEN|MACTXEN|DDMA_EN|
6645                          FW2HW_EN|RXDMA_EN|TXDMA_EN|HCI_RXDMA_EN|HCI_TXDMA_EN);         //3
6646         //Adapter->HalFunc.SetHwRegHandler( Adapter, HW_VAR_COMMAND, &tmpU1b );
6647         write_nic_word(dev, CMDR, tmpU2b); //LZM REGISTER COM 090305
6648
6649         // Loopback mode or not
6650         priv->LoopbackMode = RTL8192SU_NO_LOOPBACK; // Set no loopback as default.
6651         if(priv->LoopbackMode == RTL8192SU_NO_LOOPBACK)
6652                 tmpU1b = LBK_NORMAL;
6653         else if (priv->LoopbackMode == RTL8192SU_MAC_LOOPBACK )
6654                 tmpU1b = LBK_MAC_DLB;
6655         else
6656                 RT_TRACE(COMP_INIT, "Serious error: wrong loopback mode setting\n");
6657
6658         //Adapter->HalFunc.SetHwRegHandler( Adapter, HW_VAR_LBK_MODE, &tmpU1b);
6659         write_nic_byte(dev, LBKMD_SEL, tmpU1b);
6660
6661         // Set RCR
6662         write_nic_dword(dev, RCR, priv->ReceiveConfig);
6663         RT_TRACE(COMP_INIT, "MacConfigAfterFwDownload(): Current RCR settings(%#x)\n", priv->ReceiveConfig);
6664
6665
6666         // Set RQPN
6667         //
6668         // <Roger_Notes> 2008.08.18.
6669         // 6 endpoints:
6670         // (1) Page number on CMDQ is 0x03.
6671         // (2) Page number on BCNQ, HQ and MGTQ is 0.
6672         // (3) Page number on BKQ, BEQ, VIQ and VOQ are 0x07.
6673         // (4) Page number on PUBQ is 0xdd
6674         //
6675         // 11 endpoints:
6676         // (1) Page number on CMDQ is 0x00.
6677         // (2) Page number on BCNQ is 0x02, HQ and MGTQ are 0x03.
6678         // (3) Page number on BKQ, BEQ, VIQ and VOQ are 0x07.
6679         // (4) Page number on PUBQ is 0xd8
6680         //
6681         //write_nic_dword(Adapter, 0xa0, 0x07070707); //BKQ, BEQ, VIQ and VOQ
6682         //write_nic_byte(dev, 0xa4, 0x00); // HCCAQ
6683 #if 0    //LZM 090219
6684 #ifdef USE_SIX_USB_ENDPOINT
6685         //write_nic_dword(Adapter, 0xa5, 0x00000003); //CMDQ, MGTQ, HQ and BCNQ
6686         //write_nic_byte(dev, 0xa9, 0xdd); // PUBQ
6687         tmpU1b = read_nic_byte(dev, 0xab); // RQPN
6688         write_nic_byte(dev, 0xab, tmpU1b|BIT7|BIT6);// reduce to 6 endpoints.
6689 #else
6690         write_nic_dword(dev, 0xa5, 0x02030300); //CMDQ, MGTQ, HQ and BCNQ
6691         write_nic_byte(dev, 0xa9, 0xd8); // PUBQ
6692         tmpU1b = read_nic_byte(dev, 0xab); // RQPN
6693         write_nic_byte(dev, 0xab, (tmpU1b&(~BIT6))|BIT7); // Disable reduced endpoint.
6694 #endif
6695 #endif
6696
6697
6698         // Fix the RX FIFO issue(USB error), Rivesed by Roger, 2008-06-14
6699         tmpU1b = read_nic_byte_E(dev, 0x5C);
6700         write_nic_byte_E(dev, 0x5C, tmpU1b|BIT7);
6701
6702         //
6703         // Revise USB PHY to solve the issue of Rx payload error, Rivesed by Roger,  2008-04-10
6704         // Suggest by SD1 Alex.
6705         //
6706         // <Roger_Notes> The following operation are ONLY for USB PHY test chip.
6707         // 2008.10.07.
6708         //
6709 #if RTL8192SU_USB_PHY_TEST
6710         write_nic_byte(dev, 0x41,0xf4);
6711         write_nic_byte(dev, 0x40,0x00);
6712         write_nic_byte(dev, 0x42,0x00);
6713         write_nic_byte(dev, 0x42,0x01);
6714         write_nic_byte(dev, 0x40,0x0f);
6715         write_nic_byte(dev, 0x42,0x00);
6716         write_nic_byte(dev, 0x42,0x01);
6717 #endif
6718
6719 #if 0 //LZM 090219
6720         //
6721         // Suggested by SD1 Alex, 2008-06-14.
6722         //
6723         write_nic_byte(dev, TXOP_STALL_CTRL, 0x80);//NAV
6724
6725
6726         //
6727         // Set Data Auto Rate Fallback Retry Count register.
6728         //
6729         write_nic_dword(dev, DARFRC, 0x04010000);
6730         write_nic_dword(dev, DARFRC+4, 0x09070605);
6731         write_nic_dword(dev, RARFRC, 0x04010000);
6732         write_nic_dword(dev, RARFRC+4, 0x09070605);
6733
6734         // Set Data Auto Rate Fallback Reg. Added by Roger, 2008.09.22.
6735         for (i = 0; i < 8; i++)
6736                 write_nic_dword(dev, ARFR0+i*4, 0x1f0ffff0);
6737
6738         //
6739         // Set driver info, we only accept PHY status now.
6740         //
6741         //write_nic_byte(dev, RXDRVINFO_SZ, 4);
6742
6743         //
6744         // Aggregation length limit. Revised by Roger. 2008.09.22.
6745         //
6746         write_nic_dword(dev, AGGLEN_LMT_L, 0x66666666); // Long GI
6747         write_nic_byte(dev, AGGLEN_LMT_H, 0x06);        // Set AMPDU length to 12Kbytes for ShortGI case.
6748
6749         //
6750         // For Min Spacing configuration.
6751         //
6752         //Adapter->HalFunc.SetHwRegHandler(Adapter, HW_VAR_AMPDU_MIN_SPACE, (u8*)(&Adapter->MgntInfo.MinSpaceCfg));
6753         rtl8192SU_SetHwRegAmpduMinSpace(dev,priv->MinSpaceCfg);
6754 #endif
6755
6756         // For EFUSE init configuration.
6757         //if (IS_BOOT_FROM_EFUSE(Adapter))      // We may R/W EFUSE in EFUSE mode
6758         if (priv->bBootFromEfuse)
6759         {
6760                 u8      tempval;
6761
6762                 tempval = read_nic_byte(dev, SYS_ISO_CTRL+1);
6763                 tempval &= 0xFE;
6764                 write_nic_byte(dev, SYS_ISO_CTRL+1, tempval);
6765
6766                 // Enable LDO 2.5V for write action
6767                 //tempval = read_nic_byte(Adapter, EFUSE_TEST+3);
6768                 //write_nic_byte(Adapter, EFUSE_TEST+3, (tempval | 0x80));
6769
6770                 // Change Efuse Clock for write action
6771                 //write_nic_byte(Adapter, EFUSE_CLK, 0x03);
6772
6773                 // Change Program timing
6774                 write_nic_byte(dev, EFUSE_CTRL+3, 0x72);
6775                 //printk("!!!!!!!!!!!!!!!!!!!!!%s: write 0x33 with 0x72\n",__FUNCTION__);
6776                 RT_TRACE(COMP_INIT, "EFUSE CONFIG OK\n");
6777         }
6778
6779
6780         RT_TRACE(COMP_INIT, "<---MacConfigAfterFwDownload()\n");
6781 }
6782
6783 void rtl8192SU_HwConfigureRTL8192SUsb(struct net_device *dev)
6784 {
6785
6786         struct r8192_priv *priv = ieee80211_priv(dev);
6787         u8                      regBwOpMode = 0;
6788         u32                     regRATR = 0, regRRSR = 0;
6789         u8                      regTmp = 0;
6790         u32                     i = 0;
6791
6792         //1 This part need to modified according to the rate set we filtered!!
6793         //
6794         // Set RRSR, RATR, and BW_OPMODE registers
6795         //
6796         switch(priv->ieee80211->mode)
6797         {
6798         case WIRELESS_MODE_B:
6799                 regBwOpMode = BW_OPMODE_20MHZ;
6800                 regRATR = RATE_ALL_CCK;
6801                 regRRSR = RATE_ALL_CCK;
6802                 break;
6803         case WIRELESS_MODE_A:
6804                 regBwOpMode = BW_OPMODE_5G |BW_OPMODE_20MHZ;
6805                 regRATR = RATE_ALL_OFDM_AG;
6806                 regRRSR = RATE_ALL_OFDM_AG;
6807                 break;
6808         case WIRELESS_MODE_G:
6809                 regBwOpMode = BW_OPMODE_20MHZ;
6810                 regRATR = RATE_ALL_CCK | RATE_ALL_OFDM_AG;
6811                 regRRSR = RATE_ALL_CCK | RATE_ALL_OFDM_AG;
6812                 break;
6813         case WIRELESS_MODE_AUTO:
6814                 if (priv->bInHctTest)
6815                 {
6816                     regBwOpMode = BW_OPMODE_20MHZ;
6817                     regRATR = RATE_ALL_CCK | RATE_ALL_OFDM_AG;
6818                     regRRSR = RATE_ALL_CCK | RATE_ALL_OFDM_AG;
6819                 }
6820                 else
6821                 {
6822                     regBwOpMode = BW_OPMODE_20MHZ;
6823                     regRATR = RATE_ALL_CCK | RATE_ALL_OFDM_AG | RATE_ALL_OFDM_1SS | RATE_ALL_OFDM_2SS;
6824                     regRRSR = RATE_ALL_CCK | RATE_ALL_OFDM_AG;
6825                 }
6826                 break;
6827         case WIRELESS_MODE_N_24G:
6828                 // It support CCK rate by default.
6829                 // CCK rate will be filtered out only when associated AP does not support it.
6830                 regBwOpMode = BW_OPMODE_20MHZ;
6831                         regRATR = RATE_ALL_CCK | RATE_ALL_OFDM_AG | RATE_ALL_OFDM_1SS | RATE_ALL_OFDM_2SS;
6832                         regRRSR = RATE_ALL_CCK | RATE_ALL_OFDM_AG;
6833                 break;
6834         case WIRELESS_MODE_N_5G:
6835                 regBwOpMode = BW_OPMODE_5G;
6836                 regRATR = RATE_ALL_OFDM_AG | RATE_ALL_OFDM_1SS | RATE_ALL_OFDM_2SS;
6837                 regRRSR = RATE_ALL_OFDM_AG;
6838                 break;
6839         }
6840
6841         //
6842         // <Roger_Notes> We disable CCK response rate until FIB CCK rate IC's back.
6843         // 2008.09.23.
6844         //
6845         regTmp = read_nic_byte(dev, INIRTSMCS_SEL);
6846         regRRSR = ((regRRSR & 0x000fffff)<<8) | regTmp;
6847
6848         //
6849         // Update SIFS timing.
6850         //
6851         //priv->SifsTime = 0x0e0e0a0a;
6852         //Adapter->HalFunc.SetHwRegHandler( Adapter, HW_VAR_SIFS,  (pu1Byte)&pHalData->SifsTime);
6853         {       u8 val[4] = {0x0e, 0x0e, 0x0a, 0x0a};
6854                 // SIFS for CCK Data ACK
6855                 write_nic_byte(dev, SIFS_CCK, val[0]);
6856                 // SIFS for CCK consecutive tx like CTS data!
6857                 write_nic_byte(dev, SIFS_CCK+1, val[1]);
6858
6859                 // SIFS for OFDM Data ACK
6860                 write_nic_byte(dev, SIFS_OFDM, val[2]);
6861                 // SIFS for OFDM consecutive tx like CTS data!
6862                 write_nic_byte(dev, SIFS_OFDM+1, val[3]);
6863         }
6864
6865         write_nic_dword(dev, INIRTSMCS_SEL, regRRSR);
6866         write_nic_byte(dev, BW_OPMODE, regBwOpMode);
6867
6868         //
6869         // Suggested by SD1 Alex, 2008-06-14.
6870         //
6871         //PlatformEFIOWrite1Byte(Adapter, TXOP_STALL_CTRL, 0x80);//NAV to protect all TXOP.
6872
6873         //
6874         // Set Data Auto Rate Fallback Retry Count register.
6875         //
6876         write_nic_dword(dev, DARFRC, 0x02010000);
6877         write_nic_dword(dev, DARFRC+4, 0x06050403);
6878         write_nic_dword(dev, RARFRC, 0x02010000);
6879         write_nic_dword(dev, RARFRC+4, 0x06050403);
6880
6881         // Set Data Auto Rate Fallback Reg. Added by Roger, 2008.09.22.
6882         for (i = 0; i < 8; i++)
6883                 write_nic_dword(dev, ARFR0+i*4, 0x1f0ffff0);
6884
6885         //
6886         // Aggregation length limit. Revised by Roger. 2008.09.22.
6887         //
6888         write_nic_byte(dev, AGGLEN_LMT_H, 0x0f);        // Set AMPDU length to 12Kbytes for ShortGI case.
6889         write_nic_dword(dev, AGGLEN_LMT_L, 0xddd77442); // Long GI
6890         write_nic_dword(dev, AGGLEN_LMT_L+4, 0xfffdd772);
6891
6892         // Set NAV protection length
6893         write_nic_word(dev, NAV_PROT_LEN, 0x0080);
6894
6895         // Set TXOP stall control for several queue/HI/BCN/MGT/
6896         write_nic_byte(dev, TXOP_STALL_CTRL, 0x00); // NAV Protect next packet.
6897
6898         // Set MSDU lifetime.
6899         write_nic_byte(dev, MLT, 0x8f);
6900
6901         // Set CCK/OFDM SIFS
6902         write_nic_word(dev, SIFS_CCK, 0x0a0a); // CCK SIFS shall always be 10us.
6903         write_nic_word(dev, SIFS_OFDM, 0x0e0e);
6904
6905         write_nic_byte(dev, ACK_TIMEOUT, 0x40);
6906
6907         // CF-END Threshold
6908         write_nic_byte(dev, CFEND_TH, 0xFF);
6909
6910         //
6911         // For Min Spacing configuration.
6912         //
6913         switch(priv->rf_type)
6914         {
6915                 case RF_1T2R:
6916                 case RF_1T1R:
6917                         RT_TRACE(COMP_INIT, "Initializeadapter: RF_Type%s\n", (priv->rf_type==RF_1T1R? "(1T1R)":"(1T2R)"));
6918                         priv->MinSpaceCfg = (MAX_MSS_DENSITY_1T<<3);
6919                         break;
6920                 case RF_2T2R:
6921                 case RF_2T2R_GREEN:
6922                         RT_TRACE(COMP_INIT, "Initializeadapter:RF_Type(2T2R)\n");
6923                         priv->MinSpaceCfg = (MAX_MSS_DENSITY_2T<<3);
6924                         break;
6925         }
6926         write_nic_byte(dev, AMPDU_MIN_SPACE, priv->MinSpaceCfg);
6927
6928         //LZM 090219
6929         //
6930         // For Min Spacing configuration.
6931         //
6932         //priv->MinSpaceCfg = 0x00;
6933         //rtl8192SU_SetHwRegAmpduMinSpace(dev, priv->MinSpaceCfg);
6934 }
6935
6936 #endif
6937
6938 #ifdef RTL8192SU
6939 //      Description:    Initial HW relted registers.
6940 //
6941 //      Assumption:     This function is only invoked at driver intialization once.
6942 //
6943 //      2008.06.10, Added by Roger.
6944 bool rtl8192SU_adapter_start(struct net_device *dev)
6945 {
6946         struct r8192_priv *priv = ieee80211_priv(dev);
6947         //u32                                   dwRegRead = 0;
6948         //bool                                  init_status = true;
6949         //u32                                   ulRegRead;
6950         bool                                            rtStatus = true;
6951         //u8                                    PipeIndex;
6952         //u8                                    eRFPath, tmpU1b;
6953         u8 fw_download_times = 1;
6954
6955
6956         RT_TRACE(COMP_INIT, "--->InitializeAdapter8192SUsb()\n");
6957
6958         //pHalData->bGPIOChangeRF = FALSE;
6959
6960
6961         //
6962         // <Roger_Notes> 2008.06.15.
6963         //
6964         // Initialization Steps on RTL8192SU:
6965         // a. MAC initialization prior to sending down firmware code.
6966         // b. Download firmware code step by step(i.e., IMEM, EMEM, DMEM).
6967         // c. MAC configuration after firmware has been download successfully.
6968         // d. Initialize BB related configurations.
6969         // e. Initialize RF related configurations.
6970         // f.  Start to BulkIn transfer.
6971         //
6972
6973         //
6974         //a. MAC initialization prior to send down firmware code.
6975         //
6976 start:
6977         rtl8192SU_MacConfigBeforeFwDownloadASIC(dev);
6978
6979         //
6980         //b. Download firmware code step by step(i.e., IMEM, EMEM, DMEM).
6981         //
6982         rtStatus = FirmwareDownload92S(dev);
6983         if(rtStatus != true)
6984         {
6985                 if(fw_download_times == 1){
6986                         RT_TRACE(COMP_INIT, "InitializeAdapter8192SUsb(): Download Firmware failed once, Download again!!\n");
6987                         fw_download_times = fw_download_times + 1;
6988                         goto start;
6989                 }else{
6990                         RT_TRACE(COMP_INIT, "InitializeAdapter8192SUsb(): Download Firmware failed twice, end!!\n");
6991                 goto end;
6992         }
6993         }
6994         //
6995         //c. MAC configuration after firmware has been download successfully.
6996         //
6997         rtl8192SU_MacConfigAfterFwDownload(dev);
6998
6999         //priv->bLbusEnable = TRUE;
7000         //if(priv->RegRfOff == TRUE)
7001         //      priv->eRFPowerState = eRfOff;
7002
7003         // Save target channel
7004         // <Roger_Notes> Current Channel will be updated again later.
7005         //priv->CurrentChannel = Channel;
7006         rtStatus = PHY_MACConfig8192S(dev);//===>ok
7007         if(rtStatus != true)
7008         {
7009                 RT_TRACE(COMP_INIT, "InitializeAdapter8192SUsb(): Fail to configure MAC!!\n");
7010                 goto end;
7011         }
7012         if (1){
7013                 int i;
7014                 for (i=0; i<4; i++)
7015                         write_nic_dword(dev,WDCAPARA_ADD[i], 0x5e4322);
7016                 write_nic_byte(dev,AcmHwCtrl, 0x01);
7017         }
7018
7019
7020         //
7021         //d. Initialize BB related configurations.
7022         //
7023
7024         rtStatus = PHY_BBConfig8192S(dev);//===>ok
7025         if(rtStatus != true)
7026         {
7027                 RT_TRACE(COMP_INIT, "InitializeAdapter8192SUsb(): Fail to configure BB!!\n");
7028                 goto end;
7029         }
7030
7031         rtl8192_setBBreg(dev, rFPGA0_AnalogParameter2, 0xff, 0x58);//===>ok
7032
7033         //
7034         // e. Initialize RF related configurations.
7035         //
7036         // 2007/11/02 MH Before initalizing RF. We can not use FW to do RF-R/W.
7037         priv->Rf_Mode = RF_OP_By_SW_3wire;
7038
7039         // For RF test only from Scott's suggestion
7040         //write_nic_byte(dev, 0x27, 0xDB);
7041         //write_nic_byte(dev, 0x1B, 0x07);
7042
7043
7044         write_nic_byte(dev, AFE_XTAL_CTRL+1, 0xDB);
7045
7046         // <Roger_Notes> The following IOs are configured for each RF modules.
7047         // Enable RF module and reset RF and SDM module. 2008.11.17.
7048         if(priv->card_8192_version == VERSION_8192S_ACUT)
7049                 write_nic_byte(dev, SPS1_CTRL+3, (u8)(RF_EN|RF_RSTB|RF_SDMRSTB)); // Fix A-Cut bug.
7050         else
7051                 write_nic_byte(dev, RF_CTRL, (u8)(RF_EN|RF_RSTB|RF_SDMRSTB));
7052
7053         rtStatus = PHY_RFConfig8192S(dev);//===>ok
7054         if(rtStatus != true)
7055         {
7056                 RT_TRACE(COMP_INIT, "InitializeAdapter8192SUsb(): Fail to configure RF!!\n");
7057                 goto end;
7058         }
7059
7060
7061         // Set CCK and OFDM Block "ON"
7062         rtl8192_setBBreg(dev, rFPGA0_RFMOD, bCCKEn, 0x1);
7063         rtl8192_setBBreg(dev, rFPGA0_RFMOD, bOFDMEn, 0x1);
7064
7065         //
7066         // Turn off Radio B while RF type is 1T1R by SD3 Wilsion's request.
7067         // Revised by Roger, 2008.12.18.
7068         //
7069         if(priv->rf_type == RF_1T1R)
7070         {
7071                 // This is needed for PHY_REG after 20081219
7072                 rtl8192_setBBreg(dev, rFPGA0_RFMOD, 0xff000000, 0x03);
7073                 // This is needed for PHY_REG before 20081219
7074                 //PHY_SetBBReg(Adapter, rOFDM0_TRxPathEnable, bMaskByte0, 0x11);
7075         }
7076
7077 #if (RTL8192SU_DISABLE_IQK==0)
7078                 // For 1T2R IQK only currently.
7079                 if (priv->card_8192_version == VERSION_8192S_BCUT)
7080                 {
7081                         PHY_IQCalibrateBcut(dev);
7082                 }
7083                 else if (priv->card_8192_version == VERSION_8192S_ACUT)
7084                 {
7085                         PHY_IQCalibrate(dev);
7086                 }
7087 #endif
7088
7089         //LZM 090219
7090         // Set CCK and OFDM Block "ON"
7091         //rtl8192_setBBreg(dev, rFPGA0_RFMOD, bCCKEn, 0x1);
7092         //rtl8192_setBBreg(dev, rFPGA0_RFMOD, bOFDMEn, 0x1);
7093
7094
7095         //3//Get hardware version, do it in read eeprom?
7096         //GetHardwareVersion819xUsb(Adapter);
7097
7098         //3//
7099         //3 //Set Hardware
7100         //3//
7101         rtl8192SU_HwConfigureRTL8192SUsb(dev);//==>ok
7102
7103         //
7104         // <Roger_Notes> We set MAC address here if autoload was failed before,
7105         // otherwise IDR0 will NOT contain any value.
7106         //
7107         write_nic_dword(dev, IDR0, ((u32*)dev->dev_addr)[0]);
7108         write_nic_word(dev, IDR4, ((u16*)(dev->dev_addr + 4))[0]);
7109         if(!priv->bInHctTest)
7110         {
7111                 if(priv->ResetProgress == RESET_TYPE_NORESET)
7112                 {
7113                         //RT_TRACE(COMP_MLME, DBG_LOUD, ("Initializeadapter8192SUsb():RegWirelessMode(%#x) \n", Adapter->RegWirelessMode));
7114                         //Adapter->HalFunc.SetWirelessModeHandler(Adapter, Adapter->RegWirelessMode);
7115                         rtl8192_SetWirelessMode(dev, priv->ieee80211->mode);//===>ok
7116                 }
7117         }
7118         else
7119         {
7120                 priv->ieee80211->mode = WIRELESS_MODE_G;
7121                 rtl8192_SetWirelessMode(dev, WIRELESS_MODE_G);
7122         }
7123
7124         //Security related.
7125         //-----------------------------------------------------------------------------
7126         // Set up security related. 070106, by rcnjko:
7127         // 1. Clear all H/W keys.
7128         // 2. Enable H/W encryption/decryption.
7129         //-----------------------------------------------------------------------------
7130         //CamResetAllEntry(Adapter);
7131         //Adapter->HalFunc.EnableHWSecCfgHandler(Adapter);
7132
7133         //SecClearAllKeys(Adapter);
7134         CamResetAllEntry(dev);
7135         //SecInit(Adapter);
7136         {
7137                 u8 SECR_value = 0x0;
7138                 SECR_value |= SCR_TxEncEnable;
7139                 SECR_value |= SCR_RxDecEnable;
7140                 SECR_value |= SCR_NoSKMC;
7141                 write_nic_byte(dev, SECR, SECR_value);
7142         }
7143
7144 #if 0
7145
7146         if(pHalData->VersionID == VERSION_8192SU_A)
7147         {
7148                 // cosa add for tx power level initialization.
7149                 GetTxPowerOriginalOffset(Adapter);
7150                 SetTxPowerLevel819xUsb(Adapter, Channel);
7151         }
7152 #endif
7153
7154
7155 #ifdef TO_DO_LIST
7156
7157         //PHY_UpdateInitialGain(dev);
7158
7159         if(priv->RegRfOff == true)
7160         { // User disable RF via registry.
7161                 u8 eRFPath = 0;
7162
7163                 RT_TRACE((COMP_INIT|COMP_RF), "InitializeAdapter8192SUsb(): Turn off RF for RegRfOff ----------\n");
7164                 MgntActSet_RF_State(dev, eRfOff, RF_CHANGE_BY_SW);
7165                 // Those action will be discard in MgntActSet_RF_State because off the same state
7166                 for(eRFPath = 0; eRFPath <priv->NumTotalRFPath; eRFPath++)
7167                         rtl8192_setBBreg(dev, (RF90_RADIO_PATH_E)eRFPath, 0x4, 0xC00, 0x0);
7168         }
7169         else if(priv->RfOffReason > RF_CHANGE_BY_PS)
7170         { // H/W or S/W RF OFF before sleep.
7171                 RT_TRACE((COMP_INIT|COMP_RF), "InitializeAdapter8192SUsb(): Turn off RF for RfOffReason(%d) ----------\n", priv->RfOffReason);
7172                 MgntActSet_RF_State(dev, eRfOff, priv->RfOffReason);
7173         }
7174         else
7175         {
7176                 priv->eRFPowerState = eRfOn;
7177                 priv->RfOffReason = 0;
7178                 RT_TRACE((COMP_INIT|COMP_RF), "InitializeAdapter8192SUsb(): RF is on ----------\n");
7179         }
7180
7181 #endif
7182
7183
7184 //
7185 // f. Start to BulkIn transfer.
7186 //
7187 #ifdef TO_DO_LIST
7188
7189 #ifndef UNDER_VISTA
7190         {
7191                 u8      i;
7192                 PlatformAcquireSpinLock(Adapter, RT_RX_SPINLOCK);
7193
7194                 for(PipeIndex=0; PipeIndex < MAX_RX_QUEUE; PipeIndex++)
7195                 {
7196                         if (PipeIndex == 0)
7197                         {
7198                                 for(i=0; i<32; i++)
7199                                 HalUsbInMpdu(Adapter, PipeIndex);
7200                         }
7201                         else
7202                         {
7203                                 //HalUsbInMpdu(Adapter, PipeIndex);
7204                                 //HalUsbInMpdu(Adapter, PipeIndex);
7205                                 //HalUsbInMpdu(Adapter, PipeIndex);
7206                         }
7207                 }
7208                 PlatformReleaseSpinLock(Adapter, RT_RX_SPINLOCK);
7209         }
7210 #else
7211                 // Joseph add to 819X code base for Vista USB platform.
7212                 // This part may need to be add to Hal819xU code base. too.
7213                 PlatformUsbEnableInPipes(Adapter);
7214 #endif
7215
7216         RT_TRACE(COMP_INIT, "HighestOperaRate = %x\n", Adapter->MgntInfo.HighestOperaRate);
7217
7218         PlatformStartWorkItem( &(pHalData->RtUsbCheckForHangWorkItem) );
7219
7220         //
7221         // <Roger_EXP> The following  configurations are for ASIC verification temporally.
7222         // 2008.07.10.
7223         //
7224
7225 #endif
7226
7227         //
7228         // Read EEPROM TX power index and PHY_REG_PG.txt to capture correct
7229         // TX power index for different rate set.
7230         //
7231         //if(priv->card_8192_version >= VERSION_8192S_ACUT)
7232         {
7233                 // Get original hw reg values
7234                 PHY_GetHWRegOriginalValue(dev);
7235
7236                 // Write correct tx power index//FIXLZM
7237                 PHY_SetTxPowerLevel8192S(dev, priv->chan);
7238         }
7239
7240         {
7241         u8  tmpU1b = 0;
7242         // EEPROM R/W workaround
7243         tmpU1b = read_nic_byte(dev, MAC_PINMUX_CFG);
7244         write_nic_byte(dev, MAC_PINMUX_CFG, tmpU1b&(~GPIOMUX_EN));
7245         }
7246
7247 //
7248 //<Roger_Notes> 2008.08.19.
7249 // We return status here for temporal FPGA verification, 2008.08.19.
7250
7251 #ifdef RTL8192SU_FW_IQK
7252         write_nic_dword(dev, WFM5, FW_IQK_ENABLE);
7253         ChkFwCmdIoDone(dev);
7254 #endif
7255
7256         //
7257         // <Roger_Notes> We enable high power mechanism after NIC initialized.
7258         // 2008.11.27.
7259         //
7260         write_nic_dword(dev, WFM5, FW_RA_RESET);
7261         ChkFwCmdIoDone(dev);
7262         write_nic_dword(dev, WFM5, FW_RA_ACTIVE);
7263         ChkFwCmdIoDone(dev);
7264         write_nic_dword(dev, WFM5, FW_RA_REFRESH);
7265         ChkFwCmdIoDone(dev);
7266         write_nic_dword(dev, WFM5, FW_BB_RESET_ENABLE);
7267
7268 // <Roger_Notes> We return status here for temporal FPGA verification. 2008.05.12.
7269 //
7270
7271 // The following IO was for FPGA verification purpose. Added by Roger, 2008.09.11.
7272 #if 0
7273         // 2008/08/19 MH From SD1 Jong, we must write some register for true PHY/MAC FPGA.
7274         write_nic_byte(dev, rOFDM0_XAAGCCore1, 0x30);
7275         write_nic_byte(dev, rOFDM0_XBAGCCore1, 0x30);
7276
7277         write_nic_byte(dev, rOFDM0_RxDetector1, 0x42);
7278
7279         //write_nic_dword(Adapter, RCR, 0x817FF02F);
7280
7281         write_nic_dword(Adapter, rTxAGC_Mcs15_Mcs12, 0x06060606);
7282 #endif
7283 end:
7284 return rtStatus;
7285 }
7286
7287 #else
7288
7289 //InitializeAdapter and PhyCfg
7290 bool rtl8192_adapter_start(struct net_device *dev)
7291 {
7292         struct r8192_priv *priv = ieee80211_priv(dev);
7293         u32 dwRegRead = 0;
7294         bool init_status = true;
7295         RT_TRACE(COMP_INIT, "====>%s()\n", __FUNCTION__);
7296         priv->Rf_Mode = RF_OP_By_SW_3wire;
7297         //for ASIC power on sequence
7298         write_nic_byte_E(dev, 0x5f, 0x80);
7299         mdelay(50);
7300         write_nic_byte_E(dev, 0x5f, 0xf0);
7301         write_nic_byte_E(dev, 0x5d, 0x00);
7302         write_nic_byte_E(dev, 0x5e, 0x80);
7303         write_nic_byte(dev, 0x17, 0x37);
7304         mdelay(10);
7305 //#ifdef TO_DO_LIST
7306         priv->pFirmware->firmware_status = FW_STATUS_0_INIT;
7307         //config CPUReset Register
7308         //Firmware Reset or not?
7309         dwRegRead = read_nic_dword(dev, CPU_GEN);
7310         if (priv->pFirmware->firmware_status == FW_STATUS_0_INIT)
7311                 dwRegRead |= CPU_GEN_SYSTEM_RESET; //do nothing here?
7312         else if (priv->pFirmware->firmware_status == FW_STATUS_5_READY)
7313                 dwRegRead |= CPU_GEN_FIRMWARE_RESET;
7314         else
7315                 RT_TRACE(COMP_ERR, "ERROR in %s(): undefined firmware state(%d)\n", __FUNCTION__,   priv->pFirmware->firmware_status);
7316
7317         write_nic_dword(dev, CPU_GEN, dwRegRead);
7318         //mdelay(30);
7319         //config BB.
7320         rtl8192_BBConfig(dev);
7321
7322 #if 1
7323         //Loopback mode or not
7324         priv->LoopbackMode = RTL819xU_NO_LOOPBACK;
7325 //      priv->LoopbackMode = RTL819xU_MAC_LOOPBACK;
7326
7327         dwRegRead = read_nic_dword(dev, CPU_GEN);
7328         if (priv->LoopbackMode == RTL819xU_NO_LOOPBACK)
7329                 dwRegRead = ((dwRegRead & CPU_GEN_NO_LOOPBACK_MSK) | CPU_GEN_NO_LOOPBACK_SET);
7330         else if (priv->LoopbackMode == RTL819xU_MAC_LOOPBACK)
7331                 dwRegRead |= CPU_CCK_LOOPBACK;
7332         else
7333                 RT_TRACE(COMP_ERR, "Serious error in %s(): wrong loopback mode setting(%d)\n", __FUNCTION__,  priv->LoopbackMode);
7334
7335         write_nic_dword(dev, CPU_GEN, dwRegRead);
7336
7337         //after reset cpu, we need wait for a seconds to write in register.
7338         udelay(500);
7339
7340         //xiong add for new bitfile:usb suspend reset pin set to 1. //do we need?
7341         write_nic_byte_E(dev, 0x5f, (read_nic_byte_E(dev, 0x5f)|0x20));
7342
7343         //Set Hardware
7344         rtl8192_hwconfig(dev);
7345
7346         //turn on Tx/Rx
7347         write_nic_byte(dev, CMDR, CR_RE|CR_TE);
7348
7349         //set IDR0 here
7350         write_nic_dword(dev, MAC0, ((u32*)dev->dev_addr)[0]);
7351         write_nic_word(dev, MAC4, ((u16*)(dev->dev_addr + 4))[0]);
7352
7353         //set RCR
7354         write_nic_dword(dev, RCR, priv->ReceiveConfig);
7355
7356         //Initialize Number of Reserved Pages in Firmware Queue
7357         write_nic_dword(dev, RQPN1,  NUM_OF_PAGE_IN_FW_QUEUE_BK << RSVD_FW_QUEUE_PAGE_BK_SHIFT |\
7358                                                 NUM_OF_PAGE_IN_FW_QUEUE_BE << RSVD_FW_QUEUE_PAGE_BE_SHIFT | \
7359                                                 NUM_OF_PAGE_IN_FW_QUEUE_VI << RSVD_FW_QUEUE_PAGE_VI_SHIFT | \
7360                                                 NUM_OF_PAGE_IN_FW_QUEUE_VO <<RSVD_FW_QUEUE_PAGE_VO_SHIFT);
7361         write_nic_dword(dev, RQPN2, NUM_OF_PAGE_IN_FW_QUEUE_MGNT << RSVD_FW_QUEUE_PAGE_MGNT_SHIFT |\
7362                                                 NUM_OF_PAGE_IN_FW_QUEUE_CMD << RSVD_FW_QUEUE_PAGE_CMD_SHIFT);
7363         write_nic_dword(dev, RQPN3, APPLIED_RESERVED_QUEUE_IN_FW| \
7364                                                 NUM_OF_PAGE_IN_FW_QUEUE_BCN<<RSVD_FW_QUEUE_PAGE_BCN_SHIFT
7365 //                                              | NUM_OF_PAGE_IN_FW_QUEUE_PUB<<RSVD_FW_QUEUE_PAGE_PUB_SHIFT
7366                                                 );
7367         write_nic_dword(dev, RATR0+4*7, (RATE_ALL_OFDM_AG | RATE_ALL_CCK));
7368
7369         //Set AckTimeout
7370         // TODO: (it value is only for FPGA version). need to be changed!!2006.12.18, by Emily
7371         write_nic_byte(dev, ACK_TIMEOUT, 0x30);
7372
7373 //      RT_TRACE(COMP_INIT, "%s():priv->ResetProgress is %d\n", __FUNCTION__,priv->ResetProgress);
7374         if(priv->ResetProgress == RESET_TYPE_NORESET)
7375         rtl8192_SetWirelessMode(dev, priv->ieee80211->mode);
7376         if(priv->ResetProgress == RESET_TYPE_NORESET){
7377         CamResetAllEntry(dev);
7378         {
7379                 u8 SECR_value = 0x0;
7380                 SECR_value |= SCR_TxEncEnable;
7381                 SECR_value |= SCR_RxDecEnable;
7382                 SECR_value |= SCR_NoSKMC;
7383                 write_nic_byte(dev, SECR, SECR_value);
7384         }
7385         }
7386
7387         //Beacon related
7388         write_nic_word(dev, ATIMWND, 2);
7389         write_nic_word(dev, BCN_INTERVAL, 100);
7390
7391         {
7392 #define DEFAULT_EDCA 0x005e4332
7393                 int i;
7394                 for (i=0; i<QOS_QUEUE_NUM; i++)
7395                 write_nic_dword(dev, WDCAPARA_ADD[i], DEFAULT_EDCA);
7396         }
7397
7398         rtl8192_phy_configmac(dev);
7399
7400         if (priv->card_8192_version == (u8) VERSION_819xU_A)
7401         {
7402                 rtl8192_phy_getTxPower(dev);
7403                 rtl8192_phy_setTxPower(dev, priv->chan);
7404         }
7405
7406
7407         priv->usb_error = false;
7408         //Firmware download
7409         init_status = init_firmware(dev);
7410         if(!init_status)
7411         {
7412                 RT_TRACE(COMP_ERR,"ERR!!! %s(): Firmware download is failed\n", __FUNCTION__);
7413                 return init_status;
7414         }
7415         RT_TRACE(COMP_INIT, "%s():after firmware download\n", __FUNCTION__);
7416         //
7417 #ifdef TO_DO_LIST
7418 if(Adapter->ResetProgress == RESET_TYPE_NORESET)
7419         {
7420                 if(pMgntInfo->RegRfOff == TRUE)
7421                 { // User disable RF via registry.
7422                         RT_TRACE((COMP_INIT|COMP_RF), DBG_LOUD, ("InitializeAdapter819xUsb(): Turn off RF for RegRfOff ----------\n"));
7423                         MgntActSet_RF_State(Adapter, eRfOff, RF_CHANGE_BY_SW);
7424                         // Those action will be discard in MgntActSet_RF_State because off the same state
7425                         for(eRFPath = 0; eRFPath <pHalData->NumTotalRFPath; eRFPath++)
7426                                 PHY_SetRFReg(Adapter, (RF90_RADIO_PATH_E)eRFPath, 0x4, 0xC00, 0x0);
7427                 }
7428                 else if(pMgntInfo->RfOffReason > RF_CHANGE_BY_PS)
7429                 { // H/W or S/W RF OFF before sleep.
7430                         RT_TRACE((COMP_INIT|COMP_RF), DBG_LOUD, ("InitializeAdapter819xUsb(): Turn off RF for RfOffReason(%d) ----------\n", pMgntInfo->RfOffReason));
7431                         MgntActSet_RF_State(Adapter, eRfOff, pMgntInfo->RfOffReason);
7432                 }
7433                 else
7434                 {
7435                         pHalData->eRFPowerState = eRfOn;
7436                         pMgntInfo->RfOffReason = 0;
7437                         RT_TRACE((COMP_INIT|COMP_RF), DBG_LOUD, ("InitializeAdapter819xUsb(): RF is on ----------\n"));
7438                 }
7439         }
7440         else
7441         {
7442                 if(pHalData->eRFPowerState == eRfOff)
7443                 {
7444                         MgntActSet_RF_State(Adapter, eRfOff, pMgntInfo->RfOffReason);
7445                         // Those action will be discard in MgntActSet_RF_State because off the same state
7446                         for(eRFPath = 0; eRFPath <pHalData->NumTotalRFPath; eRFPath++)
7447                                 PHY_SetRFReg(Adapter, (RF90_RADIO_PATH_E)eRFPath, 0x4, 0xC00, 0x0);
7448                 }
7449         }
7450 #endif
7451         //config RF.
7452         if(priv->ResetProgress == RESET_TYPE_NORESET){
7453         rtl8192_phy_RFConfig(dev);
7454         RT_TRACE(COMP_INIT, "%s():after phy RF config\n", __FUNCTION__);
7455         }
7456
7457
7458         if(priv->ieee80211->FwRWRF)
7459                 // We can force firmware to do RF-R/W
7460                 priv->Rf_Mode = RF_OP_By_FW;
7461         else
7462                 priv->Rf_Mode = RF_OP_By_SW_3wire;
7463
7464
7465         rtl8192_phy_updateInitGain(dev);
7466         /*--set CCK and OFDM Block "ON"--*/
7467         rtl8192_setBBreg(dev, rFPGA0_RFMOD, bCCKEn, 0x1);
7468         rtl8192_setBBreg(dev, rFPGA0_RFMOD, bOFDMEn, 0x1);
7469
7470         if(priv->ResetProgress == RESET_TYPE_NORESET)
7471         {
7472                 //if D or C cut
7473                 u8 tmpvalue = read_nic_byte(dev, 0x301);
7474                 if(tmpvalue ==0x03)
7475                 {
7476                         priv->bDcut = TRUE;
7477                         RT_TRACE(COMP_POWER_TRACKING, "D-cut\n");
7478                 }
7479                 else
7480                 {
7481                         priv->bDcut = FALSE;
7482                         RT_TRACE(COMP_POWER_TRACKING, "C-cut\n");
7483                 }
7484                 dm_initialize_txpower_tracking(dev);
7485
7486                 if(priv->bDcut == TRUE)
7487                 {
7488                         u32 i, TempCCk;
7489                         u32 tmpRegA= rtl8192_QueryBBReg(dev,rOFDM0_XATxIQImbalance,bMaskDWord);
7490                 //      u32 tmpRegC= rtl8192_QueryBBReg(dev,rOFDM0_XCTxIQImbalance,bMaskDWord);
7491                         for(i = 0; i<TxBBGainTableLength; i++)
7492                         {
7493                                 if(tmpRegA == priv->txbbgain_table[i].txbbgain_value)
7494                                 {
7495                                         priv->rfa_txpowertrackingindex= (u8)i;
7496                                         priv->rfa_txpowertrackingindex_real= (u8)i;
7497                                         priv->rfa_txpowertracking_default= priv->rfa_txpowertrackingindex;
7498                                         break;
7499                                 }
7500                         }
7501
7502                         TempCCk = rtl8192_QueryBBReg(dev, rCCK0_TxFilter1, bMaskByte2);
7503
7504                         for(i=0 ; i<CCKTxBBGainTableLength ; i++)
7505                         {
7506
7507                                 if(TempCCk == priv->cck_txbbgain_table[i].ccktxbb_valuearray[0])
7508                                 {
7509                                         priv->cck_present_attentuation_20Mdefault=(u8) i;
7510                                         break;
7511                                 }
7512                         }
7513                         priv->cck_present_attentuation_40Mdefault= 0;
7514                         priv->cck_present_attentuation_difference= 0;
7515                         priv->cck_present_attentuation = priv->cck_present_attentuation_20Mdefault;
7516
7517         //              pMgntInfo->bTXPowerTracking = FALSE;//TEMPLY DISABLE
7518                 }
7519         }
7520         write_nic_byte(dev, 0x87, 0x0);
7521
7522
7523 #endif
7524         return init_status;
7525 }
7526
7527 #endif
7528 /* this configures registers for beacon tx and enables it via
7529  * rtl8192_beacon_tx_enable(). rtl8192_beacon_tx_disable() might
7530  * be used to stop beacon transmission
7531  */
7532 #if 0
7533 void rtl8192_start_tx_beacon(struct net_device *dev)
7534 {
7535         int i;
7536         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
7537         u16 word;
7538         DMESG("Enabling beacon TX");
7539         //write_nic_byte(dev, TX_CONF,0xe6);// TX_CONF
7540         //rtl8192_init_beacon(dev);
7541         //set_nic_txring(dev);
7542 //      rtl8192_prepare_beacon(dev);
7543         rtl8192_irq_disable(dev);
7544 //      rtl8192_beacon_tx_enable(dev);
7545         rtl8192_set_mode(dev,EPROM_CMD_CONFIG);
7546         //write_nic_byte(dev,0x9d,0x20); //DMA Poll
7547         //write_nic_word(dev,0x7a,0);
7548         //write_nic_word(dev,0x7a,0x8000);
7549
7550
7551         word  = read_nic_word(dev, BcnItv);
7552         word &= ~BcnItv_BcnItv; // clear Bcn_Itv
7553         write_nic_word(dev, BcnItv, word);
7554
7555         write_nic_word(dev, AtimWnd,
7556                        read_nic_word(dev, AtimWnd) &~ AtimWnd_AtimWnd);
7557
7558         word  = read_nic_word(dev, BCN_INTR_ITV);
7559         word &= ~BCN_INTR_ITV_MASK;
7560
7561         //word |= priv->ieee80211->beacon_interval *
7562         //      ((priv->txbeaconcount > 1)?(priv->txbeaconcount-1):1);
7563         // FIXME:FIXME check if correct ^^ worked with 0x3e8;
7564
7565         write_nic_word(dev, BCN_INTR_ITV, word);
7566
7567         //write_nic_word(dev,0x2e,0xe002);
7568         //write_nic_dword(dev,0x30,0xb8c7832e);
7569         for(i=0; i<ETH_ALEN; i++)
7570                 write_nic_byte(dev, BSSID+i, priv->ieee80211->beacon_cell_ssid[i]);
7571
7572 //      rtl8192_update_msr(dev);
7573
7574
7575         //write_nic_byte(dev,CONFIG4,3); /* !!!!!!!!!! */
7576
7577         rtl8192_set_mode(dev, EPROM_CMD_NORMAL);
7578
7579         rtl8192_irq_enable(dev);
7580
7581         /* VV !!!!!!!!!! VV*/
7582         /*
7583         rtl8192_set_mode(dev,EPROM_CMD_CONFIG);
7584         write_nic_byte(dev,0x9d,0x00);
7585         rtl8192_set_mode(dev,EPROM_CMD_NORMAL);
7586 */
7587 }
7588 #endif
7589 /***************************************************************************
7590     -------------------------------NET STUFF---------------------------
7591 ***************************************************************************/
7592
7593 static struct net_device_stats *rtl8192_stats(struct net_device *dev)
7594 {
7595         struct r8192_priv *priv = ieee80211_priv(dev);
7596
7597         return &priv->ieee80211->stats;
7598 }
7599
7600 bool
7601 HalTxCheckStuck819xUsb(
7602         struct net_device *dev
7603         )
7604 {
7605         struct r8192_priv *priv = ieee80211_priv(dev);
7606         u16             RegTxCounter = read_nic_word(dev, 0x128);
7607         bool            bStuck = FALSE;
7608         RT_TRACE(COMP_RESET,"%s():RegTxCounter is %d,TxCounter is %d\n",__FUNCTION__,RegTxCounter,priv->TxCounter);
7609         if(priv->TxCounter==RegTxCounter)
7610                 bStuck = TRUE;
7611
7612         priv->TxCounter = RegTxCounter;
7613
7614         return bStuck;
7615 }
7616
7617 /*
7618 *       <Assumption: RT_TX_SPINLOCK is acquired.>
7619 *       First added: 2006.11.19 by emily
7620 */
7621 RESET_TYPE
7622 TxCheckStuck(struct net_device *dev)
7623 {
7624         struct r8192_priv *priv = ieee80211_priv(dev);
7625         u8                      QueueID;
7626 //      PRT_TCB                 pTcb;
7627 //      u8                      ResetThreshold;
7628         bool                    bCheckFwTxCnt = false;
7629         //unsigned long flags;
7630
7631         //
7632         // Decide Stuch threshold according to current power save mode
7633         //
7634
7635 //     RT_TRACE(COMP_RESET, " ==> TxCheckStuck()\n");
7636 //           PlatformAcquireSpinLock(Adapter, RT_TX_SPINLOCK);
7637 //           spin_lock_irqsave(&priv->ieee80211->lock,flags);
7638              for (QueueID = 0; QueueID<=BEACON_QUEUE;QueueID ++)
7639              {
7640                         if(QueueID == TXCMD_QUEUE)
7641                          continue;
7642 #if 1
7643                         if((skb_queue_len(&priv->ieee80211->skb_waitQ[QueueID]) == 0)  && (skb_queue_len(&priv->ieee80211->skb_aggQ[QueueID]) == 0))
7644                                 continue;
7645 #endif
7646
7647                      bCheckFwTxCnt = true;
7648              }
7649 //           PlatformReleaseSpinLock(Adapter, RT_TX_SPINLOCK);
7650 //      spin_unlock_irqrestore(&priv->ieee80211->lock,flags);
7651 //      RT_TRACE(COMP_RESET,"bCheckFwTxCnt is %d\n",bCheckFwTxCnt);
7652 #if 1
7653         if(bCheckFwTxCnt)
7654         {
7655                 if(HalTxCheckStuck819xUsb(dev))
7656                 {
7657                         RT_TRACE(COMP_RESET, "TxCheckStuck(): Fw indicates no Tx condition! \n");
7658                         return RESET_TYPE_SILENT;
7659                 }
7660         }
7661 #endif
7662         return RESET_TYPE_NORESET;
7663 }
7664
7665 bool
7666 HalRxCheckStuck819xUsb(struct net_device *dev)
7667 {
7668         u16     RegRxCounter = read_nic_word(dev, 0x130);
7669         struct r8192_priv *priv = ieee80211_priv(dev);
7670         bool bStuck = FALSE;
7671 //#ifdef RTL8192SU
7672
7673 //#else
7674         static u8       rx_chk_cnt = 0;
7675         RT_TRACE(COMP_RESET,"%s(): RegRxCounter is %d,RxCounter is %d\n",__FUNCTION__,RegRxCounter,priv->RxCounter);
7676         // If rssi is small, we should check rx for long time because of bad rx.
7677         // or maybe it will continuous silent reset every 2 seconds.
7678         rx_chk_cnt++;
7679         if(priv->undecorated_smoothed_pwdb >= (RateAdaptiveTH_High+5))
7680         {
7681                 rx_chk_cnt = 0; //high rssi, check rx stuck right now.
7682         }
7683         else if(priv->undecorated_smoothed_pwdb < (RateAdaptiveTH_High+5) &&
7684                 ((priv->CurrentChannelBW!=HT_CHANNEL_WIDTH_20&&priv->undecorated_smoothed_pwdb>=RateAdaptiveTH_Low_40M) ||
7685                 (priv->CurrentChannelBW==HT_CHANNEL_WIDTH_20&&priv->undecorated_smoothed_pwdb>=RateAdaptiveTH_Low_20M)) )
7686         {
7687                 if(rx_chk_cnt < 2)
7688                 {
7689                         return bStuck;
7690                 }
7691                 else
7692                 {
7693                         rx_chk_cnt = 0;
7694                 }
7695         }
7696         else if(((priv->CurrentChannelBW!=HT_CHANNEL_WIDTH_20&&priv->undecorated_smoothed_pwdb<RateAdaptiveTH_Low_40M) ||
7697                 (priv->CurrentChannelBW==HT_CHANNEL_WIDTH_20&&priv->undecorated_smoothed_pwdb<RateAdaptiveTH_Low_20M)) &&
7698                 priv->undecorated_smoothed_pwdb >= VeryLowRSSI)
7699         {
7700                 if(rx_chk_cnt < 4)
7701                 {
7702                         //DbgPrint("RSSI < %d && RSSI >= %d, no check this time \n", RateAdaptiveTH_Low, VeryLowRSSI);
7703                         return bStuck;
7704                 }
7705                 else
7706                 {
7707                         rx_chk_cnt = 0;
7708                         //DbgPrint("RSSI < %d && RSSI >= %d, check this time \n", RateAdaptiveTH_Low, VeryLowRSSI);
7709                 }
7710         }
7711         else
7712         {
7713                 if(rx_chk_cnt < 8)
7714                 {
7715                         //DbgPrint("RSSI <= %d, no check this time \n", VeryLowRSSI);
7716                         return bStuck;
7717                 }
7718                 else
7719                 {
7720                         rx_chk_cnt = 0;
7721                         //DbgPrint("RSSI <= %d, check this time \n", VeryLowRSSI);
7722                 }
7723         }
7724 //#endif
7725
7726         if(priv->RxCounter==RegRxCounter)
7727                 bStuck = TRUE;
7728
7729         priv->RxCounter = RegRxCounter;
7730
7731         return bStuck;
7732 }
7733
7734 RESET_TYPE
7735 RxCheckStuck(struct net_device *dev)
7736 {
7737         struct r8192_priv *priv = ieee80211_priv(dev);
7738         //int                     i;
7739         bool        bRxCheck = FALSE;
7740
7741 //       RT_TRACE(COMP_RESET," ==> RxCheckStuck()\n");
7742         //PlatformAcquireSpinLock(Adapter, RT_RX_SPINLOCK);
7743
7744          if(priv->IrpPendingCount > 1)
7745                 bRxCheck = TRUE;
7746        //PlatformReleaseSpinLock(Adapter, RT_RX_SPINLOCK);
7747
7748 //       RT_TRACE(COMP_RESET,"bRxCheck is %d \n",bRxCheck);
7749         if(bRxCheck)
7750         {
7751                 if(HalRxCheckStuck819xUsb(dev))
7752                 {
7753                         RT_TRACE(COMP_RESET, "RxStuck Condition\n");
7754                         return RESET_TYPE_SILENT;
7755                 }
7756         }
7757         return RESET_TYPE_NORESET;
7758 }
7759
7760
7761 /**
7762 *       This function is called by Checkforhang to check whether we should ask OS to reset driver
7763 *
7764 *       \param pAdapter The adapter context for this miniport
7765 *
7766 *       Note:NIC with USB interface sholud not call this function because we cannot scan descriptor
7767 *       to judge whether there is tx stuck.
7768 *       Note: This function may be required to be rewrite for Vista OS.
7769 *       <<<Assumption: Tx spinlock has been acquired >>>
7770 *
7771 *       8185 and 8185b does not implement this function. This is added by Emily at 2006.11.24
7772 */
7773 RESET_TYPE
7774 rtl819x_ifcheck_resetornot(struct net_device *dev)
7775 {
7776         struct r8192_priv *priv = ieee80211_priv(dev);
7777         RESET_TYPE      TxResetType = RESET_TYPE_NORESET;
7778         RESET_TYPE      RxResetType = RESET_TYPE_NORESET;
7779         RT_RF_POWER_STATE       rfState;
7780
7781 #if (defined (RTL8192SU_FPGA_2MAC_VERIFICATION)||defined (RTL8192SU_ASIC_VERIFICATION))
7782         return RESET_TYPE_NORESET;
7783 #endif
7784
7785         rfState = priv->ieee80211->eRFPowerState;
7786
7787         TxResetType = TxCheckStuck(dev);
7788 #if 1
7789         if( rfState != eRfOff ||
7790                 /*ADAPTER_TEST_STATUS_FLAG(Adapter, ADAPTER_STATUS_FW_DOWNLOAD_FAILURE)) &&*/
7791                 (priv->ieee80211->iw_mode != IW_MODE_ADHOC))
7792         {
7793                 // If driver is in the status of firmware download failure , driver skips RF initialization and RF is
7794                 // in turned off state. Driver should check whether Rx stuck and do silent reset. And
7795                 // if driver is in firmware download failure status, driver should initialize RF in the following
7796                 // silent reset procedure Emily, 2008.01.21
7797
7798                 // Driver should not check RX stuck in IBSS mode because it is required to
7799                 // set Check BSSID in order to send beacon, however, if check BSSID is
7800                 // set, STA cannot hear any packet a all. Emily, 2008.04.12
7801                 RxResetType = RxCheckStuck(dev);
7802         }
7803 #endif
7804         if(TxResetType==RESET_TYPE_NORMAL || RxResetType==RESET_TYPE_NORMAL)
7805                 return RESET_TYPE_NORMAL;
7806         else if(TxResetType==RESET_TYPE_SILENT || RxResetType==RESET_TYPE_SILENT){
7807                 RT_TRACE(COMP_RESET,"%s():silent reset\n",__FUNCTION__);
7808                 return RESET_TYPE_SILENT;
7809         }
7810         else
7811                 return RESET_TYPE_NORESET;
7812
7813 }
7814
7815 void rtl8192_cancel_deferred_work(struct r8192_priv* priv);
7816 int _rtl8192_up(struct net_device *dev);
7817 int rtl8192_close(struct net_device *dev);
7818
7819
7820
7821 void
7822 CamRestoreAllEntry(     struct net_device *dev)
7823 {
7824         u8 EntryId = 0;
7825         struct r8192_priv *priv = ieee80211_priv(dev);
7826         u8*     MacAddr = priv->ieee80211->current_network.bssid;
7827
7828         static u8       CAM_CONST_ADDR[4][6] = {
7829                 {0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
7830                 {0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
7831                 {0x00, 0x00, 0x00, 0x00, 0x00, 0x02},
7832                 {0x00, 0x00, 0x00, 0x00, 0x00, 0x03}};
7833         static u8       CAM_CONST_BROAD[] =
7834                 {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
7835
7836         RT_TRACE(COMP_SEC, "CamRestoreAllEntry: \n");
7837
7838
7839         if ((priv->ieee80211->pairwise_key_type == KEY_TYPE_WEP40)||
7840             (priv->ieee80211->pairwise_key_type == KEY_TYPE_WEP104))
7841         {
7842
7843                 for(EntryId=0; EntryId<4; EntryId++)
7844                 {
7845                         {
7846                                 MacAddr = CAM_CONST_ADDR[EntryId];
7847                                 setKey(dev,
7848                                                 EntryId ,
7849                                                 EntryId,
7850                                                 priv->ieee80211->pairwise_key_type,
7851                                                 MacAddr,
7852                                                 0,
7853                                                 NULL);
7854                         }
7855                 }
7856
7857         }
7858         else if(priv->ieee80211->pairwise_key_type == KEY_TYPE_TKIP)
7859         {
7860
7861                 {
7862                         if(priv->ieee80211->iw_mode == IW_MODE_ADHOC)
7863                                 setKey(dev,
7864                                                 4,
7865                                                 0,
7866                                                 priv->ieee80211->pairwise_key_type,
7867                                                 (u8*)dev->dev_addr,
7868                                                 0,
7869                                                 NULL);
7870                         else
7871                                 setKey(dev,
7872                                                 4,
7873                                                 0,
7874                                                 priv->ieee80211->pairwise_key_type,
7875                                                 MacAddr,
7876                                                 0,
7877                                                 NULL);
7878                 }
7879         }
7880         else if(priv->ieee80211->pairwise_key_type == KEY_TYPE_CCMP)
7881         {
7882
7883                 {
7884                         if(priv->ieee80211->iw_mode == IW_MODE_ADHOC)
7885                                 setKey(dev,
7886                                                 4,
7887                                                 0,
7888                                                 priv->ieee80211->pairwise_key_type,
7889                                                 (u8*)dev->dev_addr,
7890                                                 0,
7891                                                 NULL);
7892                         else
7893                                 setKey(dev,
7894                                                 4,
7895                                                 0,
7896                                                 priv->ieee80211->pairwise_key_type,
7897                                                 MacAddr,
7898                                                 0,
7899                                                 NULL);
7900                 }
7901         }
7902
7903
7904
7905         if(priv->ieee80211->group_key_type == KEY_TYPE_TKIP)
7906         {
7907                 MacAddr = CAM_CONST_BROAD;
7908                 for(EntryId=1 ; EntryId<4 ; EntryId++)
7909                 {
7910                         {
7911                                 setKey(dev,
7912                                                 EntryId,
7913                                                 EntryId,
7914                                                 priv->ieee80211->group_key_type,
7915                                                 MacAddr,
7916                                                 0,
7917                                                 NULL);
7918                         }
7919                 }
7920                 if(priv->ieee80211->iw_mode == IW_MODE_ADHOC)
7921                                 setKey(dev,
7922                                                 0,
7923                                                 0,
7924                                                 priv->ieee80211->group_key_type,
7925                                                 CAM_CONST_ADDR[0],
7926                                                 0,
7927                                                 NULL);
7928         }
7929         else if(priv->ieee80211->group_key_type == KEY_TYPE_CCMP)
7930         {
7931                 MacAddr = CAM_CONST_BROAD;
7932                 for(EntryId=1; EntryId<4 ; EntryId++)
7933                 {
7934                         {
7935                                 setKey(dev,
7936                                                 EntryId ,
7937                                                 EntryId,
7938                                                 priv->ieee80211->group_key_type,
7939                                                 MacAddr,
7940                                                 0,
7941                                                 NULL);
7942                         }
7943                 }
7944
7945                 if(priv->ieee80211->iw_mode == IW_MODE_ADHOC)
7946                                 setKey(dev,
7947                                                 0 ,
7948                                                 0,
7949                                                 priv->ieee80211->group_key_type,
7950                                                 CAM_CONST_ADDR[0],
7951                                                 0,
7952                                                 NULL);
7953         }
7954 }
7955 //////////////////////////////////////////////////////////////
7956 // This function is used to fix Tx/Rx stop bug temporarily.
7957 // This function will do "system reset" to NIC when Tx or Rx is stuck.
7958 // The method checking Tx/Rx stuck of this function is supported by FW,
7959 // which reports Tx and Rx counter to register 0x128 and 0x130.
7960 //////////////////////////////////////////////////////////////
7961 void
7962 rtl819x_ifsilentreset(struct net_device *dev)
7963 {
7964         //OCTET_STRING asocpdu;
7965         struct r8192_priv *priv = ieee80211_priv(dev);
7966         u8      reset_times = 0;
7967         int reset_status = 0;
7968         struct ieee80211_device *ieee = priv->ieee80211;
7969
7970
7971         // 2007.07.20. If we need to check CCK stop, please uncomment this line.
7972         //bStuck = Adapter->HalFunc.CheckHWStopHandler(Adapter);
7973
7974         if(priv->ResetProgress==RESET_TYPE_NORESET)
7975         {
7976 RESET_START:
7977
7978                 RT_TRACE(COMP_RESET,"=========>Reset progress!! \n");
7979
7980                 // Set the variable for reset.
7981                 priv->ResetProgress = RESET_TYPE_SILENT;
7982 //              rtl8192_close(dev);
7983 #if 1
7984                 down(&priv->wx_sem);
7985                 if(priv->up == 0)
7986                 {
7987                         RT_TRACE(COMP_ERR,"%s():the driver is not up! return\n",__FUNCTION__);
7988                         up(&priv->wx_sem);
7989                         return ;
7990                 }
7991                 priv->up = 0;
7992                 RT_TRACE(COMP_RESET,"%s():======>start to down the driver\n",__FUNCTION__);
7993 //              if(!netif_queue_stopped(dev))
7994 //                      netif_stop_queue(dev);
7995
7996                 rtl8192_rtx_disable(dev);
7997                 rtl8192_cancel_deferred_work(priv);
7998                 deinit_hal_dm(dev);
7999                 del_timer_sync(&priv->watch_dog_timer);
8000
8001                 ieee->sync_scan_hurryup = 1;
8002                 if(ieee->state == IEEE80211_LINKED)
8003                 {
8004                         down(&ieee->wx_sem);
8005                         printk("ieee->state is IEEE80211_LINKED\n");
8006                         ieee80211_stop_send_beacons(priv->ieee80211);
8007                         del_timer_sync(&ieee->associate_timer);
8008                         cancel_delayed_work(&ieee->associate_retry_wq);
8009                         ieee80211_stop_scan(ieee);
8010                         netif_carrier_off(dev);
8011                         up(&ieee->wx_sem);
8012                 }
8013                 else{
8014                         printk("ieee->state is NOT LINKED\n");
8015                         ieee80211_softmac_stop_protocol(priv->ieee80211);                       }
8016                 up(&priv->wx_sem);
8017                 RT_TRACE(COMP_RESET,"%s():<==========down process is finished\n",__FUNCTION__);
8018         //rtl8192_irq_disable(dev);
8019                 RT_TRACE(COMP_RESET,"%s():===========>start to up the driver\n",__FUNCTION__);
8020                 reset_status = _rtl8192_up(dev);
8021
8022                 RT_TRACE(COMP_RESET,"%s():<===========up process is finished\n",__FUNCTION__);
8023                 if(reset_status == -EAGAIN)
8024                 {
8025                         if(reset_times < 3)
8026                         {
8027                                 reset_times++;
8028                                 goto RESET_START;
8029                         }
8030                         else
8031                         {
8032                                 RT_TRACE(COMP_ERR," ERR!!! %s():  Reset Failed!!\n", __FUNCTION__);
8033                         }
8034                 }
8035 #endif
8036                 ieee->is_silent_reset = 1;
8037 #if 1
8038                 EnableHWSecurityConfig8192(dev);
8039 #if 1
8040                 if(ieee->state == IEEE80211_LINKED && ieee->iw_mode == IW_MODE_INFRA)
8041                 {
8042                         ieee->set_chan(ieee->dev, ieee->current_network.channel);
8043
8044 #if 1
8045                         queue_work(ieee->wq, &ieee->associate_complete_wq);
8046 #endif
8047
8048                 }
8049                 else if(ieee->state == IEEE80211_LINKED && ieee->iw_mode == IW_MODE_ADHOC)
8050                 {
8051                         ieee->set_chan(ieee->dev, ieee->current_network.channel);
8052                         ieee->link_change(ieee->dev);
8053
8054                 //      notify_wx_assoc_event(ieee);
8055
8056                         ieee80211_start_send_beacons(ieee);
8057
8058                         if (ieee->data_hard_resume)
8059                                 ieee->data_hard_resume(ieee->dev);
8060                         netif_carrier_on(ieee->dev);
8061                 }
8062 #endif
8063
8064                 CamRestoreAllEntry(dev);
8065
8066                 priv->ResetProgress = RESET_TYPE_NORESET;
8067                 priv->reset_count++;
8068
8069                 priv->bForcedSilentReset =false;
8070                 priv->bResetInProgress = false;
8071
8072                 // For test --> force write UFWP.
8073                 write_nic_byte(dev, UFWP, 1);
8074                 RT_TRACE(COMP_RESET, "Reset finished!! ====>[%d]\n", priv->reset_count);
8075 #endif
8076         }
8077 }
8078
8079 void CAM_read_entry(
8080         struct net_device *dev,
8081         u32                     iIndex
8082 )
8083 {
8084         u32 target_command=0;
8085          u32 target_content=0;
8086          u8 entry_i=0;
8087          u32 ulStatus;
8088         s32 i=100;
8089 //      printk("=======>start read CAM\n");
8090         for(entry_i=0;entry_i<CAM_CONTENT_COUNT;entry_i++)
8091         {
8092         // polling bit, and No Write enable, and address
8093                 target_command= entry_i+CAM_CONTENT_COUNT*iIndex;
8094                 target_command= target_command | BIT31;
8095
8096         //Check polling bit is clear
8097 //      mdelay(1);
8098 #if 1
8099                 while((i--)>=0)
8100                 {
8101                         ulStatus = read_nic_dword(dev, RWCAM);
8102                         if(ulStatus & BIT31){
8103                                 continue;
8104                         }
8105                         else{
8106                                 break;
8107                         }
8108                 }
8109 #endif
8110                 write_nic_dword(dev, RWCAM, target_command);
8111                 RT_TRACE(COMP_SEC,"CAM_read_entry(): WRITE A0: %x \n",target_command);
8112          //     printk("CAM_read_entry(): WRITE A0: %lx \n",target_command);
8113                 target_content = read_nic_dword(dev, RCAMO);
8114                 RT_TRACE(COMP_SEC, "CAM_read_entry(): WRITE A8: %x \n",target_content);
8115          //     printk("CAM_read_entry(): WRITE A8: %lx \n",target_content);
8116         }
8117         printk("\n");
8118 }
8119
8120 void rtl819x_update_rxcounts(
8121         struct r8192_priv *priv,
8122         u32* TotalRxBcnNum,
8123         u32* TotalRxDataNum
8124 )
8125 {
8126         u16                     SlotIndex;
8127         u8                      i;
8128
8129         *TotalRxBcnNum = 0;
8130         *TotalRxDataNum = 0;
8131
8132         SlotIndex = (priv->ieee80211->LinkDetectInfo.SlotIndex++)%(priv->ieee80211->LinkDetectInfo.SlotNum);
8133         priv->ieee80211->LinkDetectInfo.RxBcnNum[SlotIndex] = priv->ieee80211->LinkDetectInfo.NumRecvBcnInPeriod;
8134         priv->ieee80211->LinkDetectInfo.RxDataNum[SlotIndex] = priv->ieee80211->LinkDetectInfo.NumRecvDataInPeriod;
8135         for( i=0; i<priv->ieee80211->LinkDetectInfo.SlotNum; i++ ){
8136                 *TotalRxBcnNum += priv->ieee80211->LinkDetectInfo.RxBcnNum[i];
8137                 *TotalRxDataNum += priv->ieee80211->LinkDetectInfo.RxDataNum[i];
8138         }
8139 }
8140
8141 extern  void    rtl819x_watchdog_wqcallback(struct work_struct *work)
8142 {
8143         struct delayed_work *dwork = container_of(work,struct delayed_work,work);
8144        struct r8192_priv *priv = container_of(dwork,struct r8192_priv,watch_dog_wq);
8145        struct net_device *dev = priv->ieee80211->dev;
8146         struct ieee80211_device* ieee = priv->ieee80211;
8147         RESET_TYPE      ResetType = RESET_TYPE_NORESET;
8148         static u8       check_reset_cnt=0;
8149         bool bBusyTraffic = false;
8150
8151         if(!priv->up)
8152                 return;
8153         hal_dm_watchdog(dev);
8154
8155         {//to get busy traffic condition
8156                 if(ieee->state == IEEE80211_LINKED)
8157                 {
8158                         //windows mod 666 to 100.
8159                         //if(   ieee->LinkDetectInfo.NumRxOkInPeriod> 666 ||
8160                         //      ieee->LinkDetectInfo.NumTxOkInPeriod> 666 ) {
8161                         if(     ieee->LinkDetectInfo.NumRxOkInPeriod> 100 ||
8162                                 ieee->LinkDetectInfo.NumTxOkInPeriod> 100 ) {
8163                                 bBusyTraffic = true;
8164                         }
8165                         ieee->LinkDetectInfo.NumRxOkInPeriod = 0;
8166                         ieee->LinkDetectInfo.NumTxOkInPeriod = 0;
8167                         ieee->LinkDetectInfo.bBusyTraffic = bBusyTraffic;
8168                 }
8169         }
8170         //added by amy for AP roaming
8171         {
8172                 if(priv->ieee80211->state == IEEE80211_LINKED && priv->ieee80211->iw_mode == IW_MODE_INFRA)
8173                 {
8174                         u32     TotalRxBcnNum = 0;
8175                         u32     TotalRxDataNum = 0;
8176
8177                         rtl819x_update_rxcounts(priv, &TotalRxBcnNum, &TotalRxDataNum);
8178                         if((TotalRxBcnNum+TotalRxDataNum) == 0)
8179                         {
8180                                 #ifdef TODO
8181                                 if(rfState == eRfOff)
8182                                         RT_TRACE(COMP_ERR,"========>%s()\n",__FUNCTION__);
8183                                 #endif
8184                                 printk("===>%s(): AP is power off,connect another one\n",__FUNCTION__);
8185                         //      Dot11d_Reset(dev);
8186                                 priv->ieee80211->state = IEEE80211_ASSOCIATING;
8187                                 notify_wx_assoc_event(priv->ieee80211);
8188                                 RemovePeerTS(priv->ieee80211,priv->ieee80211->current_network.bssid);
8189                                 ieee->is_roaming = true;
8190                                 priv->ieee80211->link_change(dev);
8191                                 queue_work(priv->ieee80211->wq, &priv->ieee80211->associate_procedure_wq);
8192                         }
8193                 }
8194                 priv->ieee80211->LinkDetectInfo.NumRecvBcnInPeriod=0;
8195                 priv->ieee80211->LinkDetectInfo.NumRecvDataInPeriod=0;
8196         }
8197 //      CAM_read_entry(dev,4);
8198         //check if reset the driver
8199         if(check_reset_cnt++ >= 3 && !ieee->is_roaming)
8200         {
8201                 ResetType = rtl819x_ifcheck_resetornot(dev);
8202                 check_reset_cnt = 3;
8203                 //DbgPrint("Start to check silent reset\n");
8204         }
8205         //      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);
8206 #if 1
8207         if( (priv->force_reset) || (priv->ResetProgress==RESET_TYPE_NORESET &&
8208                 (priv->bForcedSilentReset ||
8209                 (!priv->bDisableNormalResetCheck && ResetType==RESET_TYPE_SILENT)))) // This is control by OID set in Pomelo
8210         {
8211                 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);
8212                 rtl819x_ifsilentreset(dev);
8213         }
8214 #endif
8215         priv->force_reset = false;
8216         priv->bForcedSilentReset = false;
8217         priv->bResetInProgress = false;
8218         RT_TRACE(COMP_TRACE, " <==RtUsbCheckForHangWorkItemCallback()\n");
8219
8220 }
8221
8222 void watch_dog_timer_callback(unsigned long data)
8223 {
8224         struct r8192_priv *priv = ieee80211_priv((struct net_device *) data);
8225         //printk("===============>watch_dog  timer\n");
8226         queue_delayed_work(priv->priv_wq,&priv->watch_dog_wq, 0);
8227         mod_timer(&priv->watch_dog_timer, jiffies + MSECS(IEEE80211_WATCH_DOG_TIME));
8228 #if 0
8229         priv->watch_dog_timer.expires = jiffies + MSECS(IEEE80211_WATCH_DOG_TIME);
8230         add_timer(&priv->watch_dog_timer);
8231 #endif
8232 }
8233 int _rtl8192_up(struct net_device *dev)
8234 {
8235         struct r8192_priv *priv = ieee80211_priv(dev);
8236         //int i;
8237         int init_status = 0;
8238         priv->up=1;
8239         priv->ieee80211->ieee_up=1;
8240         RT_TRACE(COMP_INIT, "Bringing up iface");
8241         init_status = priv->ops->rtl819x_adapter_start(dev);
8242         if(!init_status)
8243         {
8244                 RT_TRACE(COMP_ERR,"ERR!!! %s(): initialization is failed!\n", __FUNCTION__);
8245                 priv->up=priv->ieee80211->ieee_up = 0;
8246                 return -EAGAIN;
8247         }
8248         RT_TRACE(COMP_INIT, "start adapter finished\n");
8249         rtl8192_rx_enable(dev);
8250 //      rtl8192_tx_enable(dev);
8251         if(priv->ieee80211->state != IEEE80211_LINKED)
8252         ieee80211_softmac_start_protocol(priv->ieee80211);
8253         ieee80211_reset_queue(priv->ieee80211);
8254         watch_dog_timer_callback((unsigned long) dev);
8255         if(!netif_queue_stopped(dev))
8256                 netif_start_queue(dev);
8257         else
8258                 netif_wake_queue(dev);
8259
8260         /*
8261          * Make sure that drop_unencrypted is initialized as "0"
8262          * No packets will be sent in non-security mode if we had set drop_unencrypted.
8263          * ex, After kill wpa_supplicant process, make the driver up again.
8264          * drop_unencrypted remains as "1", which is set by wpa_supplicant. 2008/12/04.john
8265          */
8266         priv->ieee80211->drop_unencrypted = 0;
8267
8268         return 0;
8269 }
8270
8271
8272 int rtl8192_open(struct net_device *dev)
8273 {
8274         struct r8192_priv *priv = ieee80211_priv(dev);
8275         int ret;
8276         down(&priv->wx_sem);
8277         ret = rtl8192_up(dev);
8278         up(&priv->wx_sem);
8279         return ret;
8280
8281 }
8282
8283
8284 int rtl8192_up(struct net_device *dev)
8285 {
8286         struct r8192_priv *priv = ieee80211_priv(dev);
8287
8288         if (priv->up == 1) return -1;
8289
8290         return _rtl8192_up(dev);
8291 }
8292
8293
8294 int rtl8192_close(struct net_device *dev)
8295 {
8296         struct r8192_priv *priv = ieee80211_priv(dev);
8297         int ret;
8298
8299         down(&priv->wx_sem);
8300
8301         ret = rtl8192_down(dev);
8302
8303         up(&priv->wx_sem);
8304
8305         return ret;
8306
8307 }
8308
8309 int rtl8192_down(struct net_device *dev)
8310 {
8311         struct r8192_priv *priv = ieee80211_priv(dev);
8312         int i;
8313
8314         if (priv->up == 0) return -1;
8315
8316         priv->up=0;
8317         priv->ieee80211->ieee_up = 0;
8318         RT_TRACE(COMP_DOWN, "==========>%s()\n", __FUNCTION__);
8319 /* FIXME */
8320         if (!netif_queue_stopped(dev))
8321                 netif_stop_queue(dev);
8322
8323         rtl8192_rtx_disable(dev);
8324         //rtl8192_irq_disable(dev);
8325
8326  /* Tx related queue release */
8327         for(i = 0; i < MAX_QUEUE_SIZE; i++) {
8328                 skb_queue_purge(&priv->ieee80211->skb_waitQ [i]);
8329         }
8330         for(i = 0; i < MAX_QUEUE_SIZE; i++) {
8331                 skb_queue_purge(&priv->ieee80211->skb_aggQ [i]);
8332         }
8333
8334         for(i = 0; i < MAX_QUEUE_SIZE; i++) {
8335                 skb_queue_purge(&priv->ieee80211->skb_drv_aggQ [i]);
8336         }
8337
8338         //as cancel_delayed_work will del work->timer, so if work is not definedas struct delayed_work, it will corrupt
8339 //      flush_scheduled_work();
8340         rtl8192_cancel_deferred_work(priv);
8341         deinit_hal_dm(dev);
8342         del_timer_sync(&priv->watch_dog_timer);
8343
8344
8345         ieee80211_softmac_stop_protocol(priv->ieee80211);
8346         memset(&priv->ieee80211->current_network, 0 , offsetof(struct ieee80211_network, list));
8347         RT_TRACE(COMP_DOWN, "<==========%s()\n", __FUNCTION__);
8348
8349                 return 0;
8350 }
8351
8352
8353 void rtl8192_commit(struct net_device *dev)
8354 {
8355         struct r8192_priv *priv = ieee80211_priv(dev);
8356         int reset_status = 0;
8357         //u8 reset_times = 0;
8358         if (priv->up == 0) return ;
8359         priv->up = 0;
8360
8361         rtl8192_cancel_deferred_work(priv);
8362         del_timer_sync(&priv->watch_dog_timer);
8363         //cancel_delayed_work(&priv->SwChnlWorkItem);
8364
8365         ieee80211_softmac_stop_protocol(priv->ieee80211);
8366
8367         //rtl8192_irq_disable(dev);
8368         rtl8192_rtx_disable(dev);
8369         reset_status = _rtl8192_up(dev);
8370
8371 }
8372
8373 /*
8374 void rtl8192_restart(struct net_device *dev)
8375 {
8376         struct r8192_priv *priv = ieee80211_priv(dev);
8377 */
8378 void rtl8192_restart(struct work_struct *work)
8379 {
8380         struct r8192_priv *priv = container_of(work, struct r8192_priv, reset_wq);
8381         struct net_device *dev = priv->ieee80211->dev;
8382
8383         down(&priv->wx_sem);
8384
8385         rtl8192_commit(dev);
8386
8387         up(&priv->wx_sem);
8388 }
8389
8390 static void r8192_set_multicast(struct net_device *dev)
8391 {
8392         struct r8192_priv *priv = ieee80211_priv(dev);
8393         short promisc;
8394
8395         //down(&priv->wx_sem);
8396
8397         /* FIXME FIXME */
8398
8399         promisc = (dev->flags & IFF_PROMISC) ? 1:0;
8400
8401         if (promisc != priv->promisc)
8402         //      rtl8192_commit(dev);
8403
8404         priv->promisc = promisc;
8405
8406         //schedule_work(&priv->reset_wq);
8407         //up(&priv->wx_sem);
8408 }
8409
8410
8411 int r8192_set_mac_adr(struct net_device *dev, void *mac)
8412 {
8413         struct r8192_priv *priv = ieee80211_priv(dev);
8414         struct sockaddr *addr = mac;
8415
8416         down(&priv->wx_sem);
8417
8418         memcpy(dev->dev_addr, addr->sa_data, ETH_ALEN);
8419
8420         schedule_work(&priv->reset_wq);
8421
8422         up(&priv->wx_sem);
8423
8424         return 0;
8425 }
8426
8427 /* based on ipw2200 driver */
8428 int rtl8192_ioctl(struct net_device *dev, struct ifreq *rq, int cmd)
8429 {
8430         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
8431         struct iwreq *wrq = (struct iwreq *)rq;
8432         int ret=-1;
8433         struct ieee80211_device *ieee = priv->ieee80211;
8434         u32 key[4];
8435         u8 broadcast_addr[6] = {0xff,0xff,0xff,0xff,0xff,0xff};
8436         u8 zero_addr[6] = {0};
8437         struct iw_point *p = &wrq->u.data;
8438         struct ieee_param *ipw = NULL;//(struct ieee_param *)wrq->u.data.pointer;
8439
8440         down(&priv->wx_sem);
8441
8442
8443      if (p->length < sizeof(struct ieee_param) || !p->pointer){
8444              ret = -EINVAL;
8445              goto out;
8446         }
8447
8448      ipw = (struct ieee_param *)kmalloc(p->length, GFP_KERNEL);
8449      if (ipw == NULL){
8450              ret = -ENOMEM;
8451              goto out;
8452      }
8453      if (copy_from_user(ipw, p->pointer, p->length)) {
8454                 kfree(ipw);
8455             ret = -EFAULT;
8456             goto out;
8457         }
8458
8459         switch (cmd) {
8460             case RTL_IOCTL_WPA_SUPPLICANT:
8461         //parse here for HW security
8462                         if (ipw->cmd == IEEE_CMD_SET_ENCRYPTION)
8463                         {
8464                                 if (ipw->u.crypt.set_tx)
8465                                 {
8466                                         if (strcmp(ipw->u.crypt.alg, "CCMP") == 0)
8467                                                 ieee->pairwise_key_type = KEY_TYPE_CCMP;
8468                                         else if (strcmp(ipw->u.crypt.alg, "TKIP") == 0)
8469                                                 ieee->pairwise_key_type = KEY_TYPE_TKIP;
8470                                         else if (strcmp(ipw->u.crypt.alg, "WEP") == 0)
8471                                         {
8472                                                 if (ipw->u.crypt.key_len == 13)
8473                                                         ieee->pairwise_key_type = KEY_TYPE_WEP104;
8474                                                 else if (ipw->u.crypt.key_len == 5)
8475                                                         ieee->pairwise_key_type = KEY_TYPE_WEP40;
8476                                         }
8477                                         else
8478                                                 ieee->pairwise_key_type = KEY_TYPE_NA;
8479
8480                                         if (ieee->pairwise_key_type)
8481                                         {
8482                                 //      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
8483                                                 if (memcmp(ieee->ap_mac_addr, zero_addr, 6) == 0)
8484                                                         ieee->iw_mode = IW_MODE_ADHOC;
8485                                                 memcpy((u8*)key, ipw->u.crypt.key, 16);
8486                                                 EnableHWSecurityConfig8192(dev);
8487                                         //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!
8488                                         //added by WB.
8489                                                 setKey(dev, 4, ipw->u.crypt.idx, ieee->pairwise_key_type, (u8*)ieee->ap_mac_addr, 0, key);
8490                                                 if (ieee->iw_mode == IW_MODE_ADHOC)
8491                                                 setKey(dev, ipw->u.crypt.idx, ipw->u.crypt.idx, ieee->pairwise_key_type, (u8*)ieee->ap_mac_addr, 0, key);
8492                                         }
8493                                 }
8494                                 else //if (ipw->u.crypt.idx) //group key use idx > 0
8495                                 {
8496                                         memcpy((u8*)key, ipw->u.crypt.key, 16);
8497                                         if (strcmp(ipw->u.crypt.alg, "CCMP") == 0)
8498                                                 ieee->group_key_type= KEY_TYPE_CCMP;
8499                                         else if (strcmp(ipw->u.crypt.alg, "TKIP") == 0)
8500                                                 ieee->group_key_type = KEY_TYPE_TKIP;
8501                                         else if (strcmp(ipw->u.crypt.alg, "WEP") == 0)
8502                                         {
8503                                                 if (ipw->u.crypt.key_len == 13)
8504                                                         ieee->group_key_type = KEY_TYPE_WEP104;
8505                                                 else if (ipw->u.crypt.key_len == 5)
8506                                                         ieee->group_key_type = KEY_TYPE_WEP40;
8507                                         }
8508                                         else
8509                                                 ieee->group_key_type = KEY_TYPE_NA;
8510
8511                                         if (ieee->group_key_type)
8512                                         {
8513                                                         setKey( dev,
8514                                                                 ipw->u.crypt.idx,
8515                                                                 ipw->u.crypt.idx,               //KeyIndex
8516                                                                 ieee->group_key_type,   //KeyType
8517                                                                 broadcast_addr, //MacAddr
8518                                                                 0,              //DefaultKey
8519                                                                 key);           //KeyContent
8520                                         }
8521                                 }
8522                         }
8523 #ifdef JOHN_HWSEC_DEBUG
8524                 //john's test 0711
8525                 printk("@@ wrq->u pointer = ");
8526                 for(i=0;i<wrq->u.data.length;i++){
8527                         if(i%10==0) printk("\n");
8528                         printk( "%8x|", ((u32*)wrq->u.data.pointer)[i] );
8529                 }
8530                 printk("\n");
8531 #endif /*JOHN_HWSEC_DEBUG*/
8532                 ret = ieee80211_wpa_supplicant_ioctl(priv->ieee80211, &wrq->u.data);
8533                 break;
8534
8535             default:
8536                 ret = -EOPNOTSUPP;
8537                 break;
8538         }
8539         kfree(ipw);
8540         ipw = NULL;
8541 out:
8542         up(&priv->wx_sem);
8543         return ret;
8544 }
8545
8546 #ifdef RTL8192SU
8547 u8 rtl8192SU_HwRateToMRate(bool bIsHT, u8 rate,bool bFirstAMPDU)
8548 {
8549
8550         u8      ret_rate = 0x02;
8551
8552         if( bFirstAMPDU )
8553         {
8554         if(!bIsHT)
8555         {
8556                 switch(rate)
8557                 {
8558
8559                         case DESC92S_RATE1M:            ret_rate = MGN_1M;              break;
8560                         case DESC92S_RATE2M:            ret_rate = MGN_2M;              break;
8561                         case DESC92S_RATE5_5M:          ret_rate = MGN_5_5M;            break;
8562                         case DESC92S_RATE11M:           ret_rate = MGN_11M;             break;
8563                         case DESC92S_RATE6M:            ret_rate = MGN_6M;              break;
8564                         case DESC92S_RATE9M:            ret_rate = MGN_9M;              break;
8565                         case DESC92S_RATE12M:           ret_rate = MGN_12M;             break;
8566                         case DESC92S_RATE18M:           ret_rate = MGN_18M;             break;
8567                         case DESC92S_RATE24M:           ret_rate = MGN_24M;             break;
8568                         case DESC92S_RATE36M:           ret_rate = MGN_36M;             break;
8569                         case DESC92S_RATE48M:           ret_rate = MGN_48M;             break;
8570                         case DESC92S_RATE54M:           ret_rate = MGN_54M;             break;
8571
8572                         default:
8573                                 RT_TRACE(COMP_RECV, "HwRateToMRate90(): Non supported Rate [%x], bIsHT = %d!!!\n", rate, bIsHT);
8574                                         break;
8575         }
8576                 }
8577                 else
8578         {
8579                 switch(rate)
8580                 {
8581
8582                         case DESC92S_RATEMCS0:  ret_rate = MGN_MCS0;            break;
8583                         case DESC92S_RATEMCS1:  ret_rate = MGN_MCS1;            break;
8584                         case DESC92S_RATEMCS2:  ret_rate = MGN_MCS2;            break;
8585                         case DESC92S_RATEMCS3:  ret_rate = MGN_MCS3;            break;
8586                         case DESC92S_RATEMCS4:  ret_rate = MGN_MCS4;            break;
8587                         case DESC92S_RATEMCS5:  ret_rate = MGN_MCS5;            break;
8588                         case DESC92S_RATEMCS6:  ret_rate = MGN_MCS6;            break;
8589                         case DESC92S_RATEMCS7:  ret_rate = MGN_MCS7;            break;
8590                         case DESC92S_RATEMCS8:  ret_rate = MGN_MCS8;            break;
8591                         case DESC92S_RATEMCS9:  ret_rate = MGN_MCS9;            break;
8592                         case DESC92S_RATEMCS10: ret_rate = MGN_MCS10;   break;
8593                         case DESC92S_RATEMCS11: ret_rate = MGN_MCS11;   break;
8594                         case DESC92S_RATEMCS12: ret_rate = MGN_MCS12;   break;
8595                         case DESC92S_RATEMCS13: ret_rate = MGN_MCS13;   break;
8596                         case DESC92S_RATEMCS14: ret_rate = MGN_MCS14;   break;
8597                         case DESC92S_RATEMCS15: ret_rate = MGN_MCS15;   break;
8598                         case DESC92S_RATEMCS32: ret_rate = (0x80|0x20); break;
8599
8600                         default:
8601                                         RT_TRACE(COMP_RECV, "HwRateToMRate92S(): Non supported Rate [%x], bIsHT = %d!!!\n",rate, bIsHT );
8602                                 break;
8603                 }
8604
8605         }
8606         }
8607         else
8608         {
8609                 switch(rate)
8610                 {
8611
8612                         case DESC92S_RATE1M:    ret_rate = MGN_1M;              break;
8613                         case DESC92S_RATE2M:    ret_rate = MGN_2M;              break;
8614                         case DESC92S_RATE5_5M:  ret_rate = MGN_5_5M;            break;
8615                         case DESC92S_RATE11M:   ret_rate = MGN_11M;             break;
8616                         case DESC92S_RATE6M:    ret_rate = MGN_6M;              break;
8617                         case DESC92S_RATE9M:    ret_rate = MGN_9M;              break;
8618                         case DESC92S_RATE12M:   ret_rate = MGN_12M;             break;
8619                         case DESC92S_RATE18M:   ret_rate = MGN_18M;             break;
8620                         case DESC92S_RATE24M:   ret_rate = MGN_24M;             break;
8621                         case DESC92S_RATE36M:   ret_rate = MGN_36M;             break;
8622                         case DESC92S_RATE48M:   ret_rate = MGN_48M;             break;
8623                         case DESC92S_RATE54M:   ret_rate = MGN_54M;             break;
8624                         case DESC92S_RATEMCS0:  ret_rate = MGN_MCS0;            break;
8625                         case DESC92S_RATEMCS1:  ret_rate = MGN_MCS1;            break;
8626                         case DESC92S_RATEMCS2:  ret_rate = MGN_MCS2;            break;
8627                         case DESC92S_RATEMCS3:  ret_rate = MGN_MCS3;            break;
8628                         case DESC92S_RATEMCS4:  ret_rate = MGN_MCS4;            break;
8629                         case DESC92S_RATEMCS5:  ret_rate = MGN_MCS5;            break;
8630                         case DESC92S_RATEMCS6:  ret_rate = MGN_MCS6;            break;
8631                         case DESC92S_RATEMCS7:  ret_rate = MGN_MCS7;            break;
8632                         case DESC92S_RATEMCS8:  ret_rate = MGN_MCS8;            break;
8633                         case DESC92S_RATEMCS9:  ret_rate = MGN_MCS9;            break;
8634                         case DESC92S_RATEMCS10: ret_rate = MGN_MCS10;   break;
8635                         case DESC92S_RATEMCS11: ret_rate = MGN_MCS11;   break;
8636                         case DESC92S_RATEMCS12: ret_rate = MGN_MCS12;   break;
8637                         case DESC92S_RATEMCS13: ret_rate = MGN_MCS13;   break;
8638                         case DESC92S_RATEMCS14: ret_rate = MGN_MCS14;   break;
8639                         case DESC92S_RATEMCS15: ret_rate = MGN_MCS15;   break;
8640                         case DESC92S_RATEMCS32: ret_rate = (0x80|0x20); break;
8641
8642                         default:
8643                                 RT_TRACE(COMP_RECV, "HwRateToMRate92S(): Non supported Rate [%x], bIsHT = %d!!!\n",rate, bIsHT );
8644                                 break;
8645                         }
8646         }
8647         return ret_rate;
8648 }
8649 #endif
8650
8651 u8 HwRateToMRate90(bool bIsHT, u8 rate)
8652 {
8653         u8  ret_rate = 0xff;
8654
8655         if(!bIsHT) {
8656                 switch(rate) {
8657                         case DESC90_RATE1M:   ret_rate = MGN_1M;         break;
8658                         case DESC90_RATE2M:   ret_rate = MGN_2M;         break;
8659                         case DESC90_RATE5_5M: ret_rate = MGN_5_5M;       break;
8660                         case DESC90_RATE11M:  ret_rate = MGN_11M;        break;
8661                         case DESC90_RATE6M:   ret_rate = MGN_6M;         break;
8662                         case DESC90_RATE9M:   ret_rate = MGN_9M;         break;
8663                         case DESC90_RATE12M:  ret_rate = MGN_12M;        break;
8664                         case DESC90_RATE18M:  ret_rate = MGN_18M;        break;
8665                         case DESC90_RATE24M:  ret_rate = MGN_24M;        break;
8666                         case DESC90_RATE36M:  ret_rate = MGN_36M;        break;
8667                         case DESC90_RATE48M:  ret_rate = MGN_48M;        break;
8668                         case DESC90_RATE54M:  ret_rate = MGN_54M;        break;
8669
8670                         default:
8671                                 ret_rate = 0xff;
8672                                 RT_TRACE(COMP_RECV, "HwRateToMRate90(): Non supported Rate [%x], bIsHT = %d!!!\n", rate, bIsHT);
8673                                 break;
8674                 }
8675
8676         } else {
8677                 switch(rate) {
8678                         case DESC90_RATEMCS0:   ret_rate = MGN_MCS0;    break;
8679                         case DESC90_RATEMCS1:   ret_rate = MGN_MCS1;    break;
8680                         case DESC90_RATEMCS2:   ret_rate = MGN_MCS2;    break;
8681                         case DESC90_RATEMCS3:   ret_rate = MGN_MCS3;    break;
8682                         case DESC90_RATEMCS4:   ret_rate = MGN_MCS4;    break;
8683                         case DESC90_RATEMCS5:   ret_rate = MGN_MCS5;    break;
8684                         case DESC90_RATEMCS6:   ret_rate = MGN_MCS6;    break;
8685                         case DESC90_RATEMCS7:   ret_rate = MGN_MCS7;    break;
8686                         case DESC90_RATEMCS8:   ret_rate = MGN_MCS8;    break;
8687                         case DESC90_RATEMCS9:   ret_rate = MGN_MCS9;    break;
8688                         case DESC90_RATEMCS10:  ret_rate = MGN_MCS10;   break;
8689                         case DESC90_RATEMCS11:  ret_rate = MGN_MCS11;   break;
8690                         case DESC90_RATEMCS12:  ret_rate = MGN_MCS12;   break;
8691                         case DESC90_RATEMCS13:  ret_rate = MGN_MCS13;   break;
8692                         case DESC90_RATEMCS14:  ret_rate = MGN_MCS14;   break;
8693                         case DESC90_RATEMCS15:  ret_rate = MGN_MCS15;   break;
8694                         case DESC90_RATEMCS32:  ret_rate = (0x80|0x20); break;
8695
8696                         default:
8697                                 ret_rate = 0xff;
8698                                 RT_TRACE(COMP_RECV, "HwRateToMRate90(): Non supported Rate [%x], bIsHT = %d!!!\n",rate, bIsHT);
8699                                 break;
8700                 }
8701         }
8702
8703         return ret_rate;
8704 }
8705
8706 /**
8707  * Function:     UpdateRxPktTimeStamp
8708  * Overview:     Recored down the TSF time stamp when receiving a packet
8709  *
8710  * Input:
8711  *       PADAPTER        Adapter
8712  *       PRT_RFD         pRfd,
8713  *
8714  * Output:
8715  *       PRT_RFD         pRfd
8716  *                               (pRfd->Status.TimeStampHigh is updated)
8717  *                               (pRfd->Status.TimeStampLow is updated)
8718  * Return:
8719  *               None
8720  */
8721 void UpdateRxPktTimeStamp8190 (struct net_device *dev, struct ieee80211_rx_stats *stats)
8722 {
8723         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
8724
8725         if(stats->bIsAMPDU && !stats->bFirstMPDU) {
8726                 stats->mac_time[0] = priv->LastRxDescTSFLow;
8727                 stats->mac_time[1] = priv->LastRxDescTSFHigh;
8728         } else {
8729                 priv->LastRxDescTSFLow = stats->mac_time[0];
8730                 priv->LastRxDescTSFHigh = stats->mac_time[1];
8731         }
8732 }
8733
8734 //by amy 080606
8735
8736 long rtl819x_translate_todbm(u8 signal_strength_index   )// 0-100 index.
8737 {
8738         long    signal_power; // in dBm.
8739
8740         // Translate to dBm (x=0.5y-95).
8741         signal_power = (long)((signal_strength_index + 1) >> 1);
8742         signal_power -= 95;
8743
8744         return signal_power;
8745 }
8746
8747
8748 /* 2008/01/22 MH We can not delcare RSSI/EVM total value of sliding window to
8749     be a local static. Otherwise, it may increase when we return from S3/S4. The
8750     value will be kept in memory or disk. We must delcare the value in adapter
8751     and it will be reinitialized when return from S3/S4. */
8752 void rtl8192_process_phyinfo(struct r8192_priv * priv,u8* buffer, struct ieee80211_rx_stats * pprevious_stats, struct ieee80211_rx_stats * pcurrent_stats)
8753 {
8754         bool bcheck = false;
8755         u8      rfpath;
8756         u32     nspatial_stream, tmp_val;
8757         //u8    i;
8758         static u32 slide_rssi_index=0, slide_rssi_statistics=0;
8759         static u32 slide_evm_index=0, slide_evm_statistics=0;
8760         static u32 last_rssi=0, last_evm=0;
8761
8762         static u32 slide_beacon_adc_pwdb_index=0, slide_beacon_adc_pwdb_statistics=0;
8763         static u32 last_beacon_adc_pwdb=0;
8764
8765         struct ieee80211_hdr_3addr *hdr;
8766         u16 sc ;
8767         unsigned int frag,seq;
8768         hdr = (struct ieee80211_hdr_3addr *)buffer;
8769         sc = le16_to_cpu(hdr->seq_ctl);
8770         frag = WLAN_GET_SEQ_FRAG(sc);
8771         seq = WLAN_GET_SEQ_SEQ(sc);
8772         //cosa add 04292008 to record the sequence number
8773         pcurrent_stats->Seq_Num = seq;
8774         //
8775         // Check whether we should take the previous packet into accounting
8776         //
8777         if(!pprevious_stats->bIsAMPDU)
8778         {
8779                 // if previous packet is not aggregated packet
8780                 bcheck = true;
8781         }else
8782         {
8783         #if 0
8784                 // if previous packet is aggregated packet, and current packet
8785                 //  (1) is not AMPDU
8786                 //  (2) is the first packet of one AMPDU
8787                 // that means the previous packet is the last one aggregated packet
8788                 if( !pcurrent_stats->bIsAMPDU || pcurrent_stats->bFirstMPDU)
8789                         bcheck = true;
8790         #endif
8791         }
8792
8793
8794         if(slide_rssi_statistics++ >= PHY_RSSI_SLID_WIN_MAX)
8795         {
8796                 slide_rssi_statistics = PHY_RSSI_SLID_WIN_MAX;
8797                 last_rssi = priv->stats.slide_signal_strength[slide_rssi_index];
8798                 priv->stats.slide_rssi_total -= last_rssi;
8799         }
8800         priv->stats.slide_rssi_total += pprevious_stats->SignalStrength;
8801
8802         priv->stats.slide_signal_strength[slide_rssi_index++] = pprevious_stats->SignalStrength;
8803         if(slide_rssi_index >= PHY_RSSI_SLID_WIN_MAX)
8804                 slide_rssi_index = 0;
8805
8806         // <1> Showed on UI for user, in dbm
8807         tmp_val = priv->stats.slide_rssi_total/slide_rssi_statistics;
8808         priv->stats.signal_strength = rtl819x_translate_todbm((u8)tmp_val);
8809         pcurrent_stats->rssi = priv->stats.signal_strength;
8810         //
8811         // If the previous packet does not match the criteria, neglect it
8812         //
8813         if(!pprevious_stats->bPacketMatchBSSID)
8814         {
8815                 if(!pprevious_stats->bToSelfBA)
8816                         return;
8817         }
8818
8819         if(!bcheck)
8820                 return;
8821
8822
8823         //rtl8190_process_cck_rxpathsel(priv,pprevious_stats);//only rtl8190 supported
8824
8825         //
8826         // Check RSSI
8827         //
8828         priv->stats.num_process_phyinfo++;
8829
8830         /* record the general signal strength to the sliding window. */
8831
8832
8833         // <2> Showed on UI for engineering
8834         // hardware does not provide rssi information for each rf path in CCK
8835         if(!pprevious_stats->bIsCCK && (pprevious_stats->bPacketToSelf || pprevious_stats->bToSelfBA))
8836         {
8837                 for (rfpath = RF90_PATH_A; rfpath < priv->NumTotalRFPath; rfpath++)
8838                 {
8839                      if (!rtl8192_phy_CheckIsLegalRFPath(priv->ieee80211->dev, rfpath))
8840                                  continue;
8841
8842                         //Fixed by Jacken 2008-03-20
8843                         if(priv->stats.rx_rssi_percentage[rfpath] == 0)
8844                         {
8845                                 priv->stats.rx_rssi_percentage[rfpath] = pprevious_stats->RxMIMOSignalStrength[rfpath];
8846                                 //DbgPrint("MIMO RSSI initialize \n");
8847                         }
8848                         if(pprevious_stats->RxMIMOSignalStrength[rfpath]  > priv->stats.rx_rssi_percentage[rfpath])
8849                         {
8850                                 priv->stats.rx_rssi_percentage[rfpath] =
8851                                         ( (priv->stats.rx_rssi_percentage[rfpath]*(Rx_Smooth_Factor-1)) +
8852                                         (pprevious_stats->RxMIMOSignalStrength[rfpath])) /(Rx_Smooth_Factor);
8853                                 priv->stats.rx_rssi_percentage[rfpath] = priv->stats.rx_rssi_percentage[rfpath]  + 1;
8854                         }
8855                         else
8856                         {
8857                                 priv->stats.rx_rssi_percentage[rfpath] =
8858                                         ( (priv->stats.rx_rssi_percentage[rfpath]*(Rx_Smooth_Factor-1)) +
8859                                         (pprevious_stats->RxMIMOSignalStrength[rfpath])) /(Rx_Smooth_Factor);
8860                         }
8861                         RT_TRACE(COMP_DBG,"priv->stats.rx_rssi_percentage[rfPath]  = %d \n" ,priv->stats.rx_rssi_percentage[rfpath] );
8862                 }
8863         }
8864
8865
8866         //
8867         // Check PWDB.
8868         //
8869         RT_TRACE(COMP_RXDESC, "Smooth %s PWDB = %d\n",
8870                                 pprevious_stats->bIsCCK? "CCK": "OFDM",
8871                                 pprevious_stats->RxPWDBAll);
8872
8873         if(pprevious_stats->bPacketBeacon)
8874         {
8875 /* record the beacon pwdb to the sliding window. */
8876                 if(slide_beacon_adc_pwdb_statistics++ >= PHY_Beacon_RSSI_SLID_WIN_MAX)
8877                 {
8878                         slide_beacon_adc_pwdb_statistics = PHY_Beacon_RSSI_SLID_WIN_MAX;
8879                         last_beacon_adc_pwdb = priv->stats.Slide_Beacon_pwdb[slide_beacon_adc_pwdb_index];
8880                         priv->stats.Slide_Beacon_Total -= last_beacon_adc_pwdb;
8881                         //DbgPrint("slide_beacon_adc_pwdb_index = %d, last_beacon_adc_pwdb = %d, Adapter->RxStats.Slide_Beacon_Total = %d\n",
8882                         //      slide_beacon_adc_pwdb_index, last_beacon_adc_pwdb, Adapter->RxStats.Slide_Beacon_Total);
8883                 }
8884                 priv->stats.Slide_Beacon_Total += pprevious_stats->RxPWDBAll;
8885                 priv->stats.Slide_Beacon_pwdb[slide_beacon_adc_pwdb_index] = pprevious_stats->RxPWDBAll;
8886                 //DbgPrint("slide_beacon_adc_pwdb_index = %d, pPreviousRfd->Status.RxPWDBAll = %d\n", slide_beacon_adc_pwdb_index, pPreviousRfd->Status.RxPWDBAll);
8887                 slide_beacon_adc_pwdb_index++;
8888                 if(slide_beacon_adc_pwdb_index >= PHY_Beacon_RSSI_SLID_WIN_MAX)
8889                         slide_beacon_adc_pwdb_index = 0;
8890                 pprevious_stats->RxPWDBAll = priv->stats.Slide_Beacon_Total/slide_beacon_adc_pwdb_statistics;
8891                 if(pprevious_stats->RxPWDBAll >= 3)
8892                         pprevious_stats->RxPWDBAll -= 3;
8893         }
8894
8895         RT_TRACE(COMP_RXDESC, "Smooth %s PWDB = %d\n",
8896                                 pprevious_stats->bIsCCK? "CCK": "OFDM",
8897                                 pprevious_stats->RxPWDBAll);
8898
8899
8900         if(pprevious_stats->bPacketToSelf || pprevious_stats->bPacketBeacon || pprevious_stats->bToSelfBA)
8901         {
8902                 if(priv->undecorated_smoothed_pwdb < 0) // initialize
8903                 {
8904                         priv->undecorated_smoothed_pwdb = pprevious_stats->RxPWDBAll;
8905                         //DbgPrint("First pwdb initialize \n");
8906                 }
8907 #if 1
8908                 if(pprevious_stats->RxPWDBAll > (u32)priv->undecorated_smoothed_pwdb)
8909                 {
8910                         priv->undecorated_smoothed_pwdb =
8911                                         ( ((priv->undecorated_smoothed_pwdb)*(Rx_Smooth_Factor-1)) +
8912                                         (pprevious_stats->RxPWDBAll)) /(Rx_Smooth_Factor);
8913                         priv->undecorated_smoothed_pwdb = priv->undecorated_smoothed_pwdb + 1;
8914                 }
8915                 else
8916                 {
8917                         priv->undecorated_smoothed_pwdb =
8918                                         ( ((priv->undecorated_smoothed_pwdb)*(Rx_Smooth_Factor-1)) +
8919                                         (pprevious_stats->RxPWDBAll)) /(Rx_Smooth_Factor);
8920                 }
8921 #else
8922                 //Fixed by Jacken 2008-03-20
8923                 if(pPreviousRfd->Status.RxPWDBAll > (u32)pHalData->UndecoratedSmoothedPWDB)
8924                 {
8925                         pHalData->UndecoratedSmoothedPWDB =
8926                                         ( ((pHalData->UndecoratedSmoothedPWDB)* 5) + (pPreviousRfd->Status.RxPWDBAll)) / 6;
8927                         pHalData->UndecoratedSmoothedPWDB = pHalData->UndecoratedSmoothedPWDB + 1;
8928                 }
8929                 else
8930                 {
8931                         pHalData->UndecoratedSmoothedPWDB =
8932                                         ( ((pHalData->UndecoratedSmoothedPWDB)* 5) + (pPreviousRfd->Status.RxPWDBAll)) / 6;
8933                 }
8934 #endif
8935
8936         }
8937
8938         //
8939         // Check EVM
8940         //
8941         /* record the general EVM to the sliding window. */
8942         if(pprevious_stats->SignalQuality == 0)
8943         {
8944         }
8945         else
8946         {
8947                 if(pprevious_stats->bPacketToSelf || pprevious_stats->bPacketBeacon || pprevious_stats->bToSelfBA){
8948                         if(slide_evm_statistics++ >= PHY_RSSI_SLID_WIN_MAX){
8949                                 slide_evm_statistics = PHY_RSSI_SLID_WIN_MAX;
8950                                 last_evm = priv->stats.slide_evm[slide_evm_index];
8951                                 priv->stats.slide_evm_total -= last_evm;
8952                         }
8953
8954                         priv->stats.slide_evm_total += pprevious_stats->SignalQuality;
8955
8956                         priv->stats.slide_evm[slide_evm_index++] = pprevious_stats->SignalQuality;
8957                         if(slide_evm_index >= PHY_RSSI_SLID_WIN_MAX)
8958                                 slide_evm_index = 0;
8959
8960                         // <1> Showed on UI for user, in percentage.
8961                         tmp_val = priv->stats.slide_evm_total/slide_evm_statistics;
8962                         priv->stats.signal_quality = tmp_val;
8963                         //cosa add 10/11/2007, Showed on UI for user in Windows Vista, for Link quality.
8964                         priv->stats.last_signal_strength_inpercent = tmp_val;
8965                 }
8966
8967                 // <2> Showed on UI for engineering
8968                 if(pprevious_stats->bPacketToSelf || pprevious_stats->bPacketBeacon || pprevious_stats->bToSelfBA)
8969                 {
8970                         for(nspatial_stream = 0; nspatial_stream<2 ; nspatial_stream++) // 2 spatial stream
8971                         {
8972                                 if(pprevious_stats->RxMIMOSignalQuality[nspatial_stream] != -1)
8973                                 {
8974                                         if(priv->stats.rx_evm_percentage[nspatial_stream] == 0) // initialize
8975                                         {
8976                                                 priv->stats.rx_evm_percentage[nspatial_stream] = pprevious_stats->RxMIMOSignalQuality[nspatial_stream];
8977                                         }
8978                                         priv->stats.rx_evm_percentage[nspatial_stream] =
8979                                                 ( (priv->stats.rx_evm_percentage[nspatial_stream]* (Rx_Smooth_Factor-1)) +
8980                                                 (pprevious_stats->RxMIMOSignalQuality[nspatial_stream]* 1)) / (Rx_Smooth_Factor);
8981                                 }
8982                         }
8983                 }
8984         }
8985
8986
8987 }
8988
8989 /*-----------------------------------------------------------------------------
8990  * Function:    rtl819x_query_rxpwrpercentage()
8991  *
8992  * Overview:
8993  *
8994  * Input:               char            antpower
8995  *
8996  * Output:              NONE
8997  *
8998  * Return:              0-100 percentage
8999  *
9000  * Revised History:
9001  *      When            Who             Remark
9002  *      05/26/2008      amy             Create Version 0 porting from windows code.
9003  *
9004  *---------------------------------------------------------------------------*/
9005 static u8 rtl819x_query_rxpwrpercentage(
9006         char            antpower
9007         )
9008 {
9009         if ((antpower <= -100) || (antpower >= 20))
9010         {
9011                 return  0;
9012         }
9013         else if (antpower >= 0)
9014         {
9015                 return  100;
9016         }
9017         else
9018         {
9019                 return  (100+antpower);
9020         }
9021
9022 }       /* QueryRxPwrPercentage */
9023
9024 static u8
9025 rtl819x_evm_dbtopercentage(
9026     char value
9027     )
9028 {
9029     char ret_val;
9030
9031     ret_val = value;
9032
9033     if(ret_val >= 0)
9034         ret_val = 0;
9035     if(ret_val <= -33)
9036         ret_val = -33;
9037     ret_val = 0 - ret_val;
9038     ret_val*=3;
9039         if(ret_val == 99)
9040                 ret_val = 100;
9041     return(ret_val);
9042 }
9043 //
9044 //      Description:
9045 //      We want good-looking for signal strength/quality
9046 //      2007/7/19 01:09, by cosa.
9047 //
9048 long
9049 rtl819x_signal_scale_mapping(
9050         long currsig
9051         )
9052 {
9053         long retsig;
9054
9055         // Step 1. Scale mapping.
9056         if(currsig >= 61 && currsig <= 100)
9057         {
9058                 retsig = 90 + ((currsig - 60) / 4);
9059         }
9060         else if(currsig >= 41 && currsig <= 60)
9061         {
9062                 retsig = 78 + ((currsig - 40) / 2);
9063         }
9064         else if(currsig >= 31 && currsig <= 40)
9065         {
9066                 retsig = 66 + (currsig - 30);
9067         }
9068         else if(currsig >= 21 && currsig <= 30)
9069         {
9070                 retsig = 54 + (currsig - 20);
9071         }
9072         else if(currsig >= 5 && currsig <= 20)
9073         {
9074                 retsig = 42 + (((currsig - 5) * 2) / 3);
9075         }
9076         else if(currsig == 4)
9077         {
9078                 retsig = 36;
9079         }
9080         else if(currsig == 3)
9081         {
9082                 retsig = 27;
9083         }
9084         else if(currsig == 2)
9085         {
9086                 retsig = 18;
9087         }
9088         else if(currsig == 1)
9089         {
9090                 retsig = 9;
9091         }
9092         else
9093         {
9094                 retsig = currsig;
9095         }
9096
9097         return retsig;
9098 }
9099
9100 #ifdef RTL8192SU
9101 /*-----------------------------------------------------------------------------
9102  * Function:    QueryRxPhyStatus8192S()
9103  *
9104  * Overview:
9105  *
9106  * Input:               NONE
9107  *
9108  * Output:              NONE
9109  *
9110  * Return:              NONE
9111  *
9112  * Revised History:
9113  *      When            Who             Remark
9114  *      06/01/2007      MHC             Create Version 0.
9115  *      06/05/2007      MHC             Accordign to HW's new data sheet, we add CCK and OFDM
9116  *                                              descriptor definition.
9117  *      07/04/2007      MHC             According to Jerry and Bryant's document. We read
9118  *                                              ir_isolation and ext_lna for RF's init value and use
9119  *                                              to compensate RSSI after receiving packets.
9120  *      09/10/2008      MHC             Modify name and PHY status field for 92SE.
9121  *      09/19/2008      MHC             Add CCK/OFDM SS/SQ for 92S series.
9122  *
9123  *---------------------------------------------------------------------------*/
9124 static void rtl8192SU_query_rxphystatus(
9125         struct r8192_priv * priv,
9126         struct ieee80211_rx_stats * pstats,
9127         rx_desc_819x_usb        *pDesc,
9128         rx_drvinfo_819x_usb  * pdrvinfo,
9129         struct ieee80211_rx_stats * precord_stats,
9130         bool bpacket_match_bssid,
9131         bool bpacket_toself,
9132         bool bPacketBeacon,
9133         bool bToSelfBA
9134         )
9135 {
9136         //PRT_RFD_STATUS                pRtRfdStatus = &(pRfd->Status);
9137         //PHY_STS_CCK_8192S_T   *pCck_buf;
9138         phy_sts_cck_819xusb_t   *       pcck_buf;
9139         phy_ofdm_rx_status_rxsc_sgien_exintfflag* prxsc;
9140         //u8                            *prxpkt;
9141         //u8                            i, max_spatial_stream, tmp_rxsnr, tmp_rxevm, rxsc_sgien_exflg;
9142         u8                              i, max_spatial_stream, rxsc_sgien_exflg;
9143         char                            rx_pwr[4], rx_pwr_all=0;
9144         //long                          rx_avg_pwr = 0;
9145         //char                          rx_snrX, rx_evmX;
9146         u8                              evm, pwdb_all;
9147         u32                             RSSI, total_rssi=0;//, total_evm=0;
9148 //      long                            signal_strength_index = 0;
9149         u8                              is_cck_rate=0;
9150         u8                              rf_rx_num = 0;
9151
9152
9153
9154         priv->stats.numqry_phystatus++;
9155
9156         is_cck_rate = rx_hal_is_cck_rate(pDesc);
9157
9158         // Record it for next packet processing
9159         memset(precord_stats, 0, sizeof(struct ieee80211_rx_stats));
9160         pstats->bPacketMatchBSSID = precord_stats->bPacketMatchBSSID = bpacket_match_bssid;
9161         pstats->bPacketToSelf = precord_stats->bPacketToSelf = bpacket_toself;
9162         pstats->bIsCCK = precord_stats->bIsCCK = is_cck_rate;//RX_HAL_IS_CCK_RATE(pDrvInfo);
9163         pstats->bPacketBeacon = precord_stats->bPacketBeacon = bPacketBeacon;
9164         pstats->bToSelfBA = precord_stats->bToSelfBA = bToSelfBA;
9165
9166 #ifndef RTL8192SU
9167         phy_sts_ofdm_819xusb_t* pofdm_buf = NULL;
9168         prxpkt = (u8*)pdrvinfo;
9169
9170         /* Move pointer to the 16th bytes. Phy status start address. */
9171         prxpkt += sizeof(rx_drvinfo_819x_usb);
9172
9173         /* Initial the cck and ofdm buffer pointer */
9174         pcck_buf = (phy_sts_cck_819xusb_t *)prxpkt;
9175         pofdm_buf = (phy_sts_ofdm_819xusb_t *)prxpkt;
9176 #endif
9177
9178         pstats->RxMIMOSignalQuality[0] = -1;
9179         pstats->RxMIMOSignalQuality[1] = -1;
9180         precord_stats->RxMIMOSignalQuality[0] = -1;
9181         precord_stats->RxMIMOSignalQuality[1] = -1;
9182
9183         if(is_cck_rate)
9184         {
9185                 u8 report;//, tmp_pwdb;
9186                 //char cck_adc_pwdb[4];
9187
9188                 // CCK Driver info Structure is not the same as OFDM packet.
9189                 pcck_buf = (phy_sts_cck_819xusb_t *)pdrvinfo;
9190
9191                 //
9192                 // (1)Hardware does not provide RSSI for CCK
9193                 //
9194
9195                 //
9196                 // (2)PWDB, Average PWDB cacluated by hardware (for rate adaptive)
9197                 //
9198
9199                 priv->stats.numqry_phystatusCCK++;
9200
9201                 if(!priv->bCckHighPower)
9202                 {
9203                         report = pcck_buf->cck_agc_rpt & 0xc0;
9204                         report = report>>6;
9205                         switch(report)
9206                         {
9207                                 //Fixed by Jacken from Bryant 2008-03-20
9208                                 //Original value is -38 , -26 , -14 , -2
9209                                 //Fixed value is -35 , -23 , -11 , 6
9210                                 case 0x3:
9211                                         rx_pwr_all = -35 - (pcck_buf->cck_agc_rpt & 0x3e);
9212                                         break;
9213                                 case 0x2:
9214                                         rx_pwr_all = -23 - (pcck_buf->cck_agc_rpt & 0x3e);
9215                                         break;
9216                                 case 0x1:
9217                                         rx_pwr_all = -11 - (pcck_buf->cck_agc_rpt & 0x3e);
9218                                         break;
9219                                 case 0x0:
9220                                         rx_pwr_all = 8 - (pcck_buf->cck_agc_rpt & 0x3e);//6->8
9221                                         break;
9222                         }
9223                 }
9224                 else
9225                 {
9226                         report = pdrvinfo->cfosho[0] & 0x60;
9227                         report = report>>5;
9228                         switch(report)
9229                         {
9230                                 case 0x3:
9231                                         rx_pwr_all = -35 - ((pcck_buf->cck_agc_rpt & 0x1f)<<1) ;
9232                                         break;
9233                                 case 0x2:
9234                                         rx_pwr_all = -23 - ((pcck_buf->cck_agc_rpt & 0x1f)<<1);
9235                                         break;
9236                                 case 0x1:
9237                                         rx_pwr_all = -11 - ((pcck_buf->cck_agc_rpt & 0x1f)<<1) ;
9238                                         break;
9239                                 case 0x0:
9240                                         rx_pwr_all = -8 - ((pcck_buf->cck_agc_rpt & 0x1f)<<1) ;//6->-8
9241                                         break;
9242                         }
9243                 }
9244
9245                 pwdb_all = rtl819x_query_rxpwrpercentage(rx_pwr_all);//check it
9246                 pstats->RxPWDBAll = precord_stats->RxPWDBAll = pwdb_all;
9247                 //pstats->RecvSignalPower = pwdb_all;
9248                 pstats->RecvSignalPower = rx_pwr_all;
9249
9250                 //
9251                 // (3) Get Signal Quality (EVM)
9252                 //
9253         //if(bpacket_match_bssid)
9254         {
9255                         u8      sq;
9256
9257                         if(pstats->RxPWDBAll > 40)
9258                         {
9259                                 sq = 100;
9260                         }else
9261                         {
9262                                 sq = pcck_buf->sq_rpt;
9263
9264                                 if(pcck_buf->sq_rpt > 64)
9265                                         sq = 0;
9266                                 else if (pcck_buf->sq_rpt < 20)
9267                                         sq = 100;
9268                                 else
9269                                         sq = ((64-sq) * 100) / 44;
9270                         }
9271                         pstats->SignalQuality = precord_stats->SignalQuality = sq;
9272                         pstats->RxMIMOSignalQuality[0] = precord_stats->RxMIMOSignalQuality[0] = sq;
9273                         pstats->RxMIMOSignalQuality[1] = precord_stats->RxMIMOSignalQuality[1] = -1;
9274                 }
9275         }
9276         else
9277         {
9278                 priv->stats.numqry_phystatusHT++;
9279
9280                 // 2008/09/19 MH For 92S debug, RX RF path always enable!!
9281                 priv->brfpath_rxenable[0] = priv->brfpath_rxenable[1] = TRUE;
9282
9283                 //
9284                 // (1)Get RSSI for HT rate
9285                 //
9286                 //for(i=RF90_PATH_A; i<priv->NumTotalRFPath; i++)
9287                 for(i=RF90_PATH_A; i<RF90_PATH_MAX; i++)
9288                 {
9289                         // 2008/01/30 MH we will judge RF RX path now.
9290                         if (priv->brfpath_rxenable[i])
9291                                 rf_rx_num++;
9292                         //else
9293                         //      continue;
9294
9295                 //if (!rtl8192_phy_CheckIsLegalRFPath(priv->ieee80211->dev, i))
9296                 //              continue;
9297
9298                         //Fixed by Jacken from Bryant 2008-03-20
9299                         //Original value is 106
9300                         //rx_pwr[i] = ((pofdm_buf->trsw_gain_X[i]&0x3F)*2) - 106;
9301                         rx_pwr[i] = ((pdrvinfo->gain_trsw[i]&0x3F)*2) - 110;
9302
9303                         /* Translate DBM to percentage. */
9304                         RSSI = rtl819x_query_rxpwrpercentage(rx_pwr[i]);        //check ok
9305                         total_rssi += RSSI;
9306                         RT_TRACE(COMP_RF, "RF-%d RXPWR=%x RSSI=%d\n", i, rx_pwr[i], RSSI);
9307
9308                         //Get Rx snr value in DB
9309                         //tmp_rxsnr =   pofdm_buf->rxsnr_X[i];
9310                         //rx_snrX = (char)(tmp_rxsnr);
9311                         //rx_snrX /= 2;
9312                         //priv->stats.rxSNRdB[i] = (long)rx_snrX;
9313                         priv->stats.rxSNRdB[i] = (long)(pdrvinfo->rxsnr[i]/2);
9314
9315                         /* Translate DBM to percentage. */
9316                         //RSSI = rtl819x_query_rxpwrpercentage(rx_pwr[i]);
9317                         //total_rssi += RSSI;
9318
9319                         /* Record Signal Strength for next packet */
9320                         //if(bpacket_match_bssid)
9321                         {
9322                                 pstats->RxMIMOSignalStrength[i] =(u8) RSSI;
9323                                 precord_stats->RxMIMOSignalStrength[i] =(u8) RSSI;
9324                         }
9325                 }
9326
9327
9328                 //
9329                 // (2)PWDB, Average PWDB cacluated by hardware (for rate adaptive)
9330                 //
9331                 //Fixed by Jacken from Bryant 2008-03-20
9332                 //Original value is 106
9333                 //rx_pwr_all = (((pofdm_buf->pwdb_all ) >> 1 )& 0x7f) -106;
9334                 rx_pwr_all = (((pdrvinfo->pwdb_all ) >> 1 )& 0x7f) -106;
9335                 pwdb_all = rtl819x_query_rxpwrpercentage(rx_pwr_all);
9336
9337                 pstats->RxPWDBAll = precord_stats->RxPWDBAll = pwdb_all;
9338                 pstats->RxPower = precord_stats->RxPower =  rx_pwr_all;
9339                 pstats->RecvSignalPower = rx_pwr_all;
9340
9341                 //
9342                 // (3)EVM of HT rate
9343                 //
9344                 //if(pdrvinfo->RxHT && pdrvinfo->RxRate>=DESC90_RATEMCS8 &&
9345                  //     pdrvinfo->RxRate<=DESC90_RATEMCS15)
9346                  if(pDesc->RxHT && pDesc->RxMCS>=DESC92S_RATEMCS8 &&
9347                         pDesc->RxMCS<=DESC92S_RATEMCS15)
9348                         max_spatial_stream = 2; //both spatial stream make sense
9349                 else
9350                         max_spatial_stream = 1; //only spatial stream 1 makes sense
9351
9352                 for(i=0; i<max_spatial_stream; i++)
9353                 {
9354                         //tmp_rxevm =   pofdm_buf->rxevm_X[i];
9355                         //rx_evmX = (char)(tmp_rxevm);
9356
9357                         // Do not use shift operation like "rx_evmX >>= 1" because the compilor of free build environment
9358                         // fill most significant bit to "zero" when doing shifting operation which may change a negative
9359                         // value to positive one, then the dbm value (which is supposed to be negative)  is not correct anymore.
9360                         //rx_evmX /= 2; //dbm
9361
9362                         //evm = rtl819x_evm_dbtopercentage(rx_evmX);
9363                         evm = rtl819x_evm_dbtopercentage( (pdrvinfo->rxevm[i] /*/ 2*/));        //dbm
9364                         RT_TRACE(COMP_RF, "RXRATE=%x RXEVM=%x EVM=%s%d\n", pDesc->RxMCS, pdrvinfo->rxevm[i], "%", evm);
9365 #if 0
9366                         EVM = SignalScaleMapping(EVM);//make it good looking, from 0~100//=====>from here
9367 #endif
9368
9369                         //if(bpacket_match_bssid)
9370                         {
9371                                 if(i==0) // Fill value in RFD, Get the first spatial stream only
9372                                         pstats->SignalQuality = precord_stats->SignalQuality = (u8)(evm & 0xff);
9373                                 pstats->RxMIMOSignalQuality[i] = precord_stats->RxMIMOSignalQuality[i] = (u8)(evm & 0xff);
9374                         }
9375                 }
9376
9377
9378                 /* record rx statistics for debug */
9379                 //rxsc_sgien_exflg = pofdm_buf->rxsc_sgien_exflg;
9380                 prxsc = (phy_ofdm_rx_status_rxsc_sgien_exintfflag *)&rxsc_sgien_exflg;
9381                 //if(pdrvinfo->BW)      //40M channel
9382                 if(pDesc->BW)   //40M channel
9383                         priv->stats.received_bwtype[1+pdrvinfo->rxsc]++;
9384                 else                            //20M channel
9385                         priv->stats.received_bwtype[0]++;
9386         }
9387
9388         //UI BSS List signal strength(in percentage), make it good looking, from 0~100.
9389         //It is assigned to the BSS List in GetValueFromBeaconOrProbeRsp().
9390         if(is_cck_rate)
9391         {
9392                 pstats->SignalStrength = precord_stats->SignalStrength = (u8)(rtl819x_signal_scale_mapping((long)pwdb_all));//PWDB_ALL;//check ok
9393
9394         }
9395         else
9396         {
9397                 //pRfd->Status.SignalStrength = pRecordRfd->Status.SignalStrength = (u8)(SignalScaleMapping(total_rssi/=RF90_PATH_MAX));//(u8)(total_rssi/=RF90_PATH_MAX);
9398                 // We can judge RX path number now.
9399                 if (rf_rx_num != 0)
9400                         pstats->SignalStrength = precord_stats->SignalStrength = (u8)(rtl819x_signal_scale_mapping((long)(total_rssi/=rf_rx_num)));
9401         }
9402 }/* QueryRxPhyStatus8192S */
9403 #else
9404 static void rtl8192_query_rxphystatus(
9405         struct r8192_priv * priv,
9406         struct ieee80211_rx_stats * pstats,
9407         rx_drvinfo_819x_usb  * pdrvinfo,
9408         struct ieee80211_rx_stats * precord_stats,
9409         bool bpacket_match_bssid,
9410         bool bpacket_toself,
9411         bool bPacketBeacon,
9412         bool bToSelfBA
9413         )
9414 {
9415         //PRT_RFD_STATUS                pRtRfdStatus = &(pRfd->Status);
9416         phy_sts_ofdm_819xusb_t* pofdm_buf;
9417         phy_sts_cck_819xusb_t   *       pcck_buf;
9418         phy_ofdm_rx_status_rxsc_sgien_exintfflag* prxsc;
9419         u8                              *prxpkt;
9420         u8                              i, max_spatial_stream, tmp_rxsnr, tmp_rxevm, rxsc_sgien_exflg;
9421         char                            rx_pwr[4], rx_pwr_all=0;
9422         //long                          rx_avg_pwr = 0;
9423         char                            rx_snrX, rx_evmX;
9424         u8                              evm, pwdb_all;
9425         u32                             RSSI, total_rssi=0;//, total_evm=0;
9426 //      long                            signal_strength_index = 0;
9427         u8                              is_cck_rate=0;
9428         u8                              rf_rx_num = 0;
9429
9430
9431         priv->stats.numqry_phystatus++;
9432
9433         is_cck_rate = rx_hal_is_cck_rate(pdrvinfo);
9434
9435         // Record it for next packet processing
9436         memset(precord_stats, 0, sizeof(struct ieee80211_rx_stats));
9437         pstats->bPacketMatchBSSID = precord_stats->bPacketMatchBSSID = bpacket_match_bssid;
9438         pstats->bPacketToSelf = precord_stats->bPacketToSelf = bpacket_toself;
9439         pstats->bIsCCK = precord_stats->bIsCCK = is_cck_rate;//RX_HAL_IS_CCK_RATE(pDrvInfo);
9440         pstats->bPacketBeacon = precord_stats->bPacketBeacon = bPacketBeacon;
9441         pstats->bToSelfBA = precord_stats->bToSelfBA = bToSelfBA;
9442
9443         prxpkt = (u8*)pdrvinfo;
9444
9445         /* Move pointer to the 16th bytes. Phy status start address. */
9446         prxpkt += sizeof(rx_drvinfo_819x_usb);
9447
9448         /* Initial the cck and ofdm buffer pointer */
9449         pcck_buf = (phy_sts_cck_819xusb_t *)prxpkt;
9450         pofdm_buf = (phy_sts_ofdm_819xusb_t *)prxpkt;
9451
9452         pstats->RxMIMOSignalQuality[0] = -1;
9453         pstats->RxMIMOSignalQuality[1] = -1;
9454         precord_stats->RxMIMOSignalQuality[0] = -1;
9455         precord_stats->RxMIMOSignalQuality[1] = -1;
9456
9457         if(is_cck_rate)
9458         {
9459                 //
9460                 // (1)Hardware does not provide RSSI for CCK
9461                 //
9462
9463                 //
9464                 // (2)PWDB, Average PWDB cacluated by hardware (for rate adaptive)
9465                 //
9466                 u8 report;//, cck_agc_rpt;
9467
9468                 priv->stats.numqry_phystatusCCK++;
9469
9470                 if(!priv->bCckHighPower)
9471                 {
9472                         report = pcck_buf->cck_agc_rpt & 0xc0;
9473                         report = report>>6;
9474                         switch(report)
9475                         {
9476                                 //Fixed by Jacken from Bryant 2008-03-20
9477                                 //Original value is -38 , -26 , -14 , -2
9478                                 //Fixed value is -35 , -23 , -11 , 6
9479                                 case 0x3:
9480                                         rx_pwr_all = -35 - (pcck_buf->cck_agc_rpt & 0x3e);
9481                                         break;
9482                                 case 0x2:
9483                                         rx_pwr_all = -23 - (pcck_buf->cck_agc_rpt & 0x3e);
9484                                         break;
9485                                 case 0x1:
9486                                         rx_pwr_all = -11 - (pcck_buf->cck_agc_rpt & 0x3e);
9487                                         break;
9488                                 case 0x0:
9489                                         rx_pwr_all = 6 - (pcck_buf->cck_agc_rpt & 0x3e);
9490                                         break;
9491                         }
9492                 }
9493                 else
9494                 {
9495                         report = pcck_buf->cck_agc_rpt & 0x60;
9496                         report = report>>5;
9497                         switch(report)
9498                         {
9499                                 case 0x3:
9500                                         rx_pwr_all = -35 - ((pcck_buf->cck_agc_rpt & 0x1f)<<1) ;
9501                                         break;
9502                                 case 0x2:
9503                                         rx_pwr_all = -23 - ((pcck_buf->cck_agc_rpt & 0x1f)<<1);
9504                                         break;
9505                                 case 0x1:
9506                                         rx_pwr_all = -11 - ((pcck_buf->cck_agc_rpt & 0x1f)<<1) ;
9507                                         break;
9508                                 case 0x0:
9509                                         rx_pwr_all = 6 - ((pcck_buf->cck_agc_rpt & 0x1f)<<1) ;
9510                                         break;
9511                         }
9512                 }
9513
9514                 pwdb_all = rtl819x_query_rxpwrpercentage(rx_pwr_all);
9515                 pstats->RxPWDBAll = precord_stats->RxPWDBAll = pwdb_all;
9516                 pstats->RecvSignalPower = pwdb_all;
9517
9518                 //
9519                 // (3) Get Signal Quality (EVM)
9520                 //
9521                 //if(bpacket_match_bssid)
9522                 {
9523                         u8      sq;
9524
9525                         if(pstats->RxPWDBAll > 40)
9526                         {
9527                                 sq = 100;
9528                         }else
9529                         {
9530                                 sq = pcck_buf->sq_rpt;
9531
9532                                 if(pcck_buf->sq_rpt > 64)
9533                                         sq = 0;
9534                                 else if (pcck_buf->sq_rpt < 20)
9535                                         sq = 100;
9536                                 else
9537                                         sq = ((64-sq) * 100) / 44;
9538                         }
9539                         pstats->SignalQuality = precord_stats->SignalQuality = sq;
9540                         pstats->RxMIMOSignalQuality[0] = precord_stats->RxMIMOSignalQuality[0] = sq;
9541                         pstats->RxMIMOSignalQuality[1] = precord_stats->RxMIMOSignalQuality[1] = -1;
9542                 }
9543         }
9544         else
9545         {
9546                 priv->stats.numqry_phystatusHT++;
9547                 //
9548                 // (1)Get RSSI for HT rate
9549                 //
9550                 for(i=RF90_PATH_A; i<priv->NumTotalRFPath; i++)
9551                 {
9552                         // 2008/01/30 MH we will judge RF RX path now.
9553                         if (priv->brfpath_rxenable[i])
9554                                 rf_rx_num++;
9555                         else
9556                                 continue;
9557
9558                 if (!rtl8192_phy_CheckIsLegalRFPath(priv->ieee80211->dev, i))
9559                                 continue;
9560
9561                         //Fixed by Jacken from Bryant 2008-03-20
9562                         //Original value is 106
9563                         rx_pwr[i] = ((pofdm_buf->trsw_gain_X[i]&0x3F)*2) - 106;
9564
9565                         //Get Rx snr value in DB
9566                         tmp_rxsnr =     pofdm_buf->rxsnr_X[i];
9567                         rx_snrX = (char)(tmp_rxsnr);
9568                         //rx_snrX >>= 1;;
9569                         rx_snrX /= 2;
9570                         priv->stats.rxSNRdB[i] = (long)rx_snrX;
9571
9572                         /* Translate DBM to percentage. */
9573                         RSSI = rtl819x_query_rxpwrpercentage(rx_pwr[i]);
9574                         total_rssi += RSSI;
9575
9576                         /* Record Signal Strength for next packet */
9577                         //if(bpacket_match_bssid)
9578                         {
9579                                 pstats->RxMIMOSignalStrength[i] =(u8) RSSI;
9580                                 precord_stats->RxMIMOSignalStrength[i] =(u8) RSSI;
9581                         }
9582                 }
9583
9584
9585                 //
9586                 // (2)PWDB, Average PWDB cacluated by hardware (for rate adaptive)
9587                 //
9588                 //Fixed by Jacken from Bryant 2008-03-20
9589                 //Original value is 106
9590                 rx_pwr_all = (((pofdm_buf->pwdb_all ) >> 1 )& 0x7f) -106;
9591                 pwdb_all = rtl819x_query_rxpwrpercentage(rx_pwr_all);
9592
9593                 pstats->RxPWDBAll = precord_stats->RxPWDBAll = pwdb_all;
9594                 pstats->RxPower = precord_stats->RxPower =  rx_pwr_all;
9595
9596                 //
9597                 // (3)EVM of HT rate
9598                 //
9599                 if(pdrvinfo->RxHT && pdrvinfo->RxRate>=DESC90_RATEMCS8 &&
9600                         pdrvinfo->RxRate<=DESC90_RATEMCS15)
9601                         max_spatial_stream = 2; //both spatial stream make sense
9602                 else
9603                         max_spatial_stream = 1; //only spatial stream 1 makes sense
9604
9605                 for(i=0; i<max_spatial_stream; i++)
9606                 {
9607                         tmp_rxevm =     pofdm_buf->rxevm_X[i];
9608                         rx_evmX = (char)(tmp_rxevm);
9609
9610                         // Do not use shift operation like "rx_evmX >>= 1" because the compilor of free build environment
9611                         // fill most significant bit to "zero" when doing shifting operation which may change a negative
9612                         // value to positive one, then the dbm value (which is supposed to be negative)  is not correct anymore.
9613                         rx_evmX /= 2;   //dbm
9614
9615                         evm = rtl819x_evm_dbtopercentage(rx_evmX);
9616 #if 0
9617                         EVM = SignalScaleMapping(EVM);//make it good looking, from 0~100
9618 #endif
9619                         //if(bpacket_match_bssid)
9620                         {
9621                                 if(i==0) // Fill value in RFD, Get the first spatial stream only
9622                                         pstats->SignalQuality = precord_stats->SignalQuality = (u8)(evm & 0xff);
9623                                 pstats->RxMIMOSignalQuality[i] = precord_stats->RxMIMOSignalQuality[i] = (u8)(evm & 0xff);
9624                         }
9625                 }
9626
9627
9628                 /* record rx statistics for debug */
9629                 rxsc_sgien_exflg = pofdm_buf->rxsc_sgien_exflg;
9630                 prxsc = (phy_ofdm_rx_status_rxsc_sgien_exintfflag *)&rxsc_sgien_exflg;
9631                 if(pdrvinfo->BW)        //40M channel
9632                         priv->stats.received_bwtype[1+prxsc->rxsc]++;
9633                 else                            //20M channel
9634                         priv->stats.received_bwtype[0]++;
9635         }
9636
9637         //UI BSS List signal strength(in percentage), make it good looking, from 0~100.
9638         //It is assigned to the BSS List in GetValueFromBeaconOrProbeRsp().
9639         if(is_cck_rate)
9640         {
9641                 pstats->SignalStrength = precord_stats->SignalStrength = (u8)(rtl819x_signal_scale_mapping((long)pwdb_all));//PWDB_ALL;
9642
9643         }
9644         else
9645         {
9646                 //pRfd->Status.SignalStrength = pRecordRfd->Status.SignalStrength = (u8)(SignalScaleMapping(total_rssi/=RF90_PATH_MAX));//(u8)(total_rssi/=RF90_PATH_MAX);
9647                 // We can judge RX path number now.
9648                 if (rf_rx_num != 0)
9649                         pstats->SignalStrength = precord_stats->SignalStrength = (u8)(rtl819x_signal_scale_mapping((long)(total_rssi/=rf_rx_num)));
9650         }
9651 }       /* QueryRxPhyStatus8190Pci */
9652 #endif
9653
9654 void
9655 rtl8192_record_rxdesc_forlateruse(
9656         struct ieee80211_rx_stats *     psrc_stats,
9657         struct ieee80211_rx_stats *     ptarget_stats
9658 )
9659 {
9660         ptarget_stats->bIsAMPDU = psrc_stats->bIsAMPDU;
9661         ptarget_stats->bFirstMPDU = psrc_stats->bFirstMPDU;
9662         ptarget_stats->Seq_Num = psrc_stats->Seq_Num;
9663 }
9664
9665 #ifdef RTL8192SU
9666 static void rtl8192SU_query_rxphystatus(
9667         struct r8192_priv * priv,
9668         struct ieee80211_rx_stats * pstats,
9669         rx_desc_819x_usb        *pDesc,
9670         rx_drvinfo_819x_usb  * pdrvinfo,
9671         struct ieee80211_rx_stats * precord_stats,
9672         bool bpacket_match_bssid,
9673         bool bpacket_toself,
9674         bool bPacketBeacon,
9675         bool bToSelfBA
9676         );
9677 void rtl8192SU_TranslateRxSignalStuff(struct sk_buff *skb,
9678                                    struct ieee80211_rx_stats * pstats,
9679                                    rx_desc_819x_usb     *pDesc,
9680                                    rx_drvinfo_819x_usb  *pdrvinfo)
9681 {
9682         // TODO: We must only check packet for current MAC address. Not finish
9683         rtl8192_rx_info *info = (struct rtl8192_rx_info *)skb->cb;
9684         struct net_device *dev=info->dev;
9685         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
9686         bool bpacket_match_bssid, bpacket_toself;
9687         bool bPacketBeacon=FALSE, bToSelfBA=FALSE;
9688         static struct ieee80211_rx_stats  previous_stats;
9689         struct ieee80211_hdr_3addr *hdr;//by amy
9690        u16 fc,type;
9691
9692         // Get Signal Quality for only RX data queue (but not command queue)
9693
9694         u8* tmp_buf;
9695         //u16 tmp_buf_len = 0;
9696         u8  *praddr;
9697
9698         /* Get MAC frame start address. */
9699         tmp_buf = (u8*)skb->data;// + get_rxpacket_shiftbytes_819xusb(pstats);
9700
9701         hdr = (struct ieee80211_hdr_3addr *)tmp_buf;
9702         fc = le16_to_cpu(hdr->frame_ctl);
9703         type = WLAN_FC_GET_TYPE(fc);
9704         praddr = hdr->addr1;
9705
9706         /* Check if the received packet is acceptabe. */
9707         bpacket_match_bssid = ((IEEE80211_FTYPE_CTL != type) &&
9708                                                         (eqMacAddr(priv->ieee80211->current_network.bssid,  (fc & IEEE80211_FCTL_TODS)? hdr->addr1 : (fc & IEEE80211_FCTL_FROMDS )? hdr->addr2 : hdr->addr3))
9709                                                                  && (!pstats->bHwError) && (!pstats->bCRC)&& (!pstats->bICV));
9710         bpacket_toself =  bpacket_match_bssid & (eqMacAddr(praddr, priv->ieee80211->dev->dev_addr));
9711
9712 #if 1//cosa
9713                 if(WLAN_FC_GET_FRAMETYPE(fc)== IEEE80211_STYPE_BEACON)
9714                 {
9715                         bPacketBeacon = true;
9716                         //DbgPrint("Beacon 2, MatchBSSID = %d, ToSelf = %d \n", bPacketMatchBSSID, bPacketToSelf);
9717                 }
9718                 if(WLAN_FC_GET_FRAMETYPE(fc) == IEEE80211_STYPE_BLOCKACK)
9719                 {
9720                         if((eqMacAddr(praddr,dev->dev_addr)))
9721                                 bToSelfBA = true;
9722                                 //DbgPrint("BlockAck, MatchBSSID = %d, ToSelf = %d \n", bPacketMatchBSSID, bPacketToSelf);
9723                 }
9724
9725 #endif
9726
9727
9728         if(bpacket_match_bssid)
9729         {
9730                 priv->stats.numpacket_matchbssid++;
9731         }
9732         if(bpacket_toself){
9733                 priv->stats.numpacket_toself++;
9734         }
9735         //
9736         // Process PHY information for previous packet (RSSI/PWDB/EVM)
9737         //
9738         // Because phy information is contained in the last packet of AMPDU only, so driver
9739         // should process phy information of previous packet
9740         rtl8192_process_phyinfo(priv, tmp_buf, &previous_stats, pstats);
9741         rtl8192SU_query_rxphystatus(priv, pstats, pDesc, pdrvinfo, &previous_stats, bpacket_match_bssid,bpacket_toself,bPacketBeacon,bToSelfBA);
9742         rtl8192_record_rxdesc_forlateruse(pstats, &previous_stats);
9743
9744 }
9745 #else
9746 void TranslateRxSignalStuff819xUsb(struct sk_buff *skb,
9747                                    struct ieee80211_rx_stats * pstats,
9748                                    rx_drvinfo_819x_usb  *pdrvinfo)
9749 {
9750         // TODO: We must only check packet for current MAC address. Not finish
9751         rtl8192_rx_info *info = (struct rtl8192_rx_info *)skb->cb;
9752         struct net_device *dev=info->dev;
9753         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
9754         bool bpacket_match_bssid, bpacket_toself;
9755         bool bPacketBeacon=FALSE, bToSelfBA=FALSE;
9756         static struct ieee80211_rx_stats  previous_stats;
9757         struct ieee80211_hdr_3addr *hdr;//by amy
9758        u16 fc,type;
9759
9760         // Get Signal Quality for only RX data queue (but not command queue)
9761
9762         u8* tmp_buf;
9763         //u16 tmp_buf_len = 0;
9764         u8  *praddr;
9765
9766         /* Get MAC frame start address. */
9767         tmp_buf = (u8*)skb->data;// + get_rxpacket_shiftbytes_819xusb(pstats);
9768
9769         hdr = (struct ieee80211_hdr_3addr *)tmp_buf;
9770         fc = le16_to_cpu(hdr->frame_ctl);
9771         type = WLAN_FC_GET_TYPE(fc);
9772         praddr = hdr->addr1;
9773
9774         /* Check if the received packet is acceptabe. */
9775         bpacket_match_bssid = ((IEEE80211_FTYPE_CTL != type) &&
9776                                                         (eqMacAddr(priv->ieee80211->current_network.bssid,  (fc & IEEE80211_FCTL_TODS)? hdr->addr1 : (fc & IEEE80211_FCTL_FROMDS )? hdr->addr2 : hdr->addr3))
9777                                                                  && (!pstats->bHwError) && (!pstats->bCRC)&& (!pstats->bICV));
9778         bpacket_toself =  bpacket_match_bssid & (eqMacAddr(praddr, priv->ieee80211->dev->dev_addr));
9779
9780 #if 1//cosa
9781                 if(WLAN_FC_GET_FRAMETYPE(fc)== IEEE80211_STYPE_BEACON)
9782                 {
9783                         bPacketBeacon = true;
9784                         //DbgPrint("Beacon 2, MatchBSSID = %d, ToSelf = %d \n", bPacketMatchBSSID, bPacketToSelf);
9785                 }
9786                 if(WLAN_FC_GET_FRAMETYPE(fc) == IEEE80211_STYPE_BLOCKACK)
9787                 {
9788                         if((eqMacAddr(praddr,dev->dev_addr)))
9789                                 bToSelfBA = true;
9790                                 //DbgPrint("BlockAck, MatchBSSID = %d, ToSelf = %d \n", bPacketMatchBSSID, bPacketToSelf);
9791                 }
9792
9793 #endif
9794
9795
9796         if(bpacket_match_bssid)
9797         {
9798                 priv->stats.numpacket_matchbssid++;
9799         }
9800         if(bpacket_toself){
9801                 priv->stats.numpacket_toself++;
9802         }
9803         //
9804         // Process PHY information for previous packet (RSSI/PWDB/EVM)
9805         //
9806         // Because phy information is contained in the last packet of AMPDU only, so driver
9807         // should process phy information of previous packet
9808         rtl8192_process_phyinfo(priv, tmp_buf, &previous_stats, pstats);
9809         rtl8192_query_rxphystatus(priv, pstats, pdrvinfo, &previous_stats, bpacket_match_bssid,bpacket_toself,bPacketBeacon,bToSelfBA);
9810         rtl8192_record_rxdesc_forlateruse(pstats, &previous_stats);
9811
9812 }
9813 #endif
9814
9815 /**
9816 * Function:     UpdateReceivedRateHistogramStatistics
9817 * Overview:     Recored down the received data rate
9818 *
9819 * Input:
9820 *       struct net_device *dev
9821 *       struct ieee80211_rx_stats *stats
9822 *
9823 * Output:
9824 *
9825 *                       (priv->stats.ReceivedRateHistogram[] is updated)
9826 * Return:
9827 *               None
9828 */
9829 void
9830 UpdateReceivedRateHistogramStatistics8190(
9831         struct net_device *dev,
9832         struct ieee80211_rx_stats *stats
9833         )
9834 {
9835         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
9836         u32 rcvType=1;   //0: Total, 1:OK, 2:CRC, 3:ICV
9837         u32 rateIndex;
9838         u32 preamble_guardinterval;  //1: short preamble/GI, 0: long preamble/GI
9839
9840
9841         if(stats->bCRC)
9842         rcvType = 2;
9843         else if(stats->bICV)
9844         rcvType = 3;
9845
9846         if(stats->bShortPreamble)
9847         preamble_guardinterval = 1;// short
9848         else
9849         preamble_guardinterval = 0;// long
9850
9851         switch(stats->rate)
9852         {
9853                 //
9854                 // CCK rate
9855                 //
9856                 case MGN_1M:    rateIndex = 0;  break;
9857                 case MGN_2M:    rateIndex = 1;  break;
9858                 case MGN_5_5M:  rateIndex = 2;  break;
9859                 case MGN_11M:   rateIndex = 3;  break;
9860                 //
9861                 // Legacy OFDM rate
9862                 //
9863                 case MGN_6M:    rateIndex = 4;  break;
9864                 case MGN_9M:    rateIndex = 5;  break;
9865                 case MGN_12M:   rateIndex = 6;  break;
9866                 case MGN_18M:   rateIndex = 7;  break;
9867                 case MGN_24M:   rateIndex = 8;  break;
9868                 case MGN_36M:   rateIndex = 9;  break;
9869                 case MGN_48M:   rateIndex = 10; break;
9870                 case MGN_54M:   rateIndex = 11; break;
9871                 //
9872                 // 11n High throughput rate
9873                 //
9874                 case MGN_MCS0:  rateIndex = 12; break;
9875                 case MGN_MCS1:  rateIndex = 13; break;
9876                 case MGN_MCS2:  rateIndex = 14; break;
9877                 case MGN_MCS3:  rateIndex = 15; break;
9878                 case MGN_MCS4:  rateIndex = 16; break;
9879                 case MGN_MCS5:  rateIndex = 17; break;
9880                 case MGN_MCS6:  rateIndex = 18; break;
9881                 case MGN_MCS7:  rateIndex = 19; break;
9882                 case MGN_MCS8:  rateIndex = 20; break;
9883                 case MGN_MCS9:  rateIndex = 21; break;
9884                 case MGN_MCS10: rateIndex = 22; break;
9885                 case MGN_MCS11: rateIndex = 23; break;
9886                 case MGN_MCS12: rateIndex = 24; break;
9887                 case MGN_MCS13: rateIndex = 25; break;
9888                 case MGN_MCS14: rateIndex = 26; break;
9889                 case MGN_MCS15: rateIndex = 27; break;
9890                 default:        rateIndex = 28; break;
9891         }
9892     priv->stats.received_preamble_GI[preamble_guardinterval][rateIndex]++;
9893     priv->stats.received_rate_histogram[0][rateIndex]++; //total
9894     priv->stats.received_rate_histogram[rcvType][rateIndex]++;
9895 }
9896
9897 #ifdef RTL8192SU
9898 void rtl8192SU_query_rxdesc_status(struct sk_buff *skb, struct ieee80211_rx_stats *stats, bool bIsRxAggrSubframe)
9899 {
9900         rtl8192_rx_info *info = (struct rtl8192_rx_info *)skb->cb;
9901         struct net_device *dev=info->dev;
9902         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
9903         //rx_desc_819x_usb *desc = (rx_desc_819x_usb *)skb->data;
9904         rx_drvinfo_819x_usb  *driver_info = NULL;
9905
9906         //PRT_RFD_STATUS                                pRtRfdStatus = &pRfd->Status;
9907         //PHAL_DATA_8192SUSB                    pHalData = GET_HAL_DATA(Adapter);
9908         //pu1Byte               pDesc = (pu1Byte)pDescIn;
9909         //PRX_DRIVER_INFO_8192S         pDrvInfo;
9910
9911         rx_desc_819x_usb *desc = (rx_desc_819x_usb *)skb->data;
9912
9913         if(0)
9914         {
9915                 int m = 0;
9916                 printk("========================");
9917                 for(m=0; m<skb->len; m++){
9918                         if((m%32) == 0)
9919                                 printk("\n");
9920                         printk("%2x ",((u8*)skb->data)[m]);
9921                 }
9922                 printk("\n========================\n");
9923
9924         }
9925
9926
9927         //
9928         //Get Rx Descriptor Raw Information
9929         //
9930         stats->Length = desc->Length ;
9931         stats->RxDrvInfoSize = desc->RxDrvInfoSize*RX_DRV_INFO_SIZE_UNIT;
9932         stats->RxBufShift = (desc->Shift)&0x03;
9933         stats->bICV = desc->ICV;
9934         stats->bCRC = desc->CRC32;
9935         stats->bHwError = stats->bCRC|stats->bICV;
9936         stats->Decrypted = !desc->SWDec;//RTL8190 set this bit to indicate that Hw does not decrypt packet
9937         stats->bIsAMPDU = (desc->AMSDU==1);
9938         stats->bFirstMPDU = (desc->PAGGR==1) && (desc->FAGGR==1);
9939         stats->bShortPreamble = desc->SPLCP;
9940         stats->RxIs40MHzPacket = (desc->BW==1);
9941         stats->TimeStampLow = desc->TSFL;
9942
9943         if((desc->FAGGR==1) || (desc->PAGGR==1))
9944         {// Rx A-MPDU
9945                 RT_TRACE(COMP_RXDESC, "FirstAGGR = %d, PartAggr = %d\n", desc->FAGGR, desc->PAGGR);
9946         }
9947 //YJ,test,090310
9948 if(stats->bHwError)
9949 {
9950         if(stats->bICV)
9951                 printk("%s: Receive ICV error!!!!!!!!!!!!!!!!!!!!!!\n", __FUNCTION__);
9952         if(stats->bCRC)
9953                 printk("%s: Receive CRC error!!!!!!!!!!!!!!!!!!!!!!\n", __FUNCTION__);
9954 }
9955
9956         if(IS_UNDER_11N_AES_MODE(priv->ieee80211))
9957         {
9958                 // Always received ICV error packets in AES mode.
9959                 // This fixed HW later MIC write bug.
9960                 if(stats->bICV && !stats->bCRC)
9961                 {
9962                         stats->bICV = FALSE;
9963                         stats->bHwError = FALSE;
9964                 }
9965         }
9966
9967         // Transform HwRate to MRate
9968         if(!stats->bHwError)
9969                 //stats->DataRate = HwRateToMRate(
9970                 //      (BOOLEAN)GET_RX_DESC_RXHT(pDesc),
9971                 //      (u1Byte)GET_RX_DESC_RXMCS(pDesc),
9972                 //      (BOOLEAN)GET_RX_DESC_PAGGR(pDesc));
9973                 stats->rate = rtl8192SU_HwRateToMRate(desc->RxHT, desc->RxMCS, desc->PAGGR);
9974         else
9975                 stats->rate = MGN_1M;
9976
9977         //
9978         // Collect Rx rate/AMPDU/TSFL
9979         //
9980         //UpdateRxdRateHistogramStatistics8192S(Adapter, pRfd);
9981         //UpdateRxAMPDUHistogramStatistics8192S(Adapter, pRfd);
9982         //UpdateRxPktTimeStamp8192S(Adapter, pRfd);
9983         UpdateReceivedRateHistogramStatistics8190(dev, stats);
9984         //UpdateRxAMPDUHistogramStatistics8192S(dev, stats);    //FIXLZM
9985         UpdateRxPktTimeStamp8190(dev, stats);
9986
9987         //
9988         // Get PHY Status and RSVD parts.
9989         // <Roger_Notes> It only appears on last aggregated packet.
9990         //
9991         if (desc->PHYStatus)
9992         {
9993                 //driver_info = (rx_drvinfo_819x_usb *)(skb->data + RX_DESC_SIZE + stats->RxBufShift);
9994                 driver_info = (rx_drvinfo_819x_usb *)(skb->data + sizeof(rx_desc_819x_usb) + \
9995                                 stats->RxBufShift);
9996                 if(0)
9997                 {
9998                         int m = 0;
9999                         printk("========================\n");
10000                         printk("RX_DESC_SIZE:%d, RxBufShift:%d, RxDrvInfoSize:%d\n",
10001                                         RX_DESC_SIZE, stats->RxBufShift, stats->RxDrvInfoSize);
10002                         for(m=0; m<32; m++){
10003                                printk("%2x ",((u8*)driver_info)[m]);
10004                         }
10005                         printk("\n========================\n");
10006
10007                 }
10008
10009         }
10010
10011         //YJ,add,090107
10012         skb_pull(skb, sizeof(rx_desc_819x_usb));
10013         //YJ,add,090107,end
10014
10015         //
10016         // Get Total offset of MPDU Frame Body
10017         //
10018         if((stats->RxBufShift + stats->RxDrvInfoSize) > 0)
10019         {
10020                 stats->bShift = 1;
10021                 //YJ,add,090107
10022                 skb_pull(skb, stats->RxBufShift + stats->RxDrvInfoSize);
10023                 //YJ,add,090107,end
10024         }
10025
10026         //
10027         // Get PHY Status and RSVD parts.
10028         // <Roger_Notes> It only appears on last aggregated packet.
10029         //
10030         if (desc->PHYStatus)
10031         {
10032                 rtl8192SU_TranslateRxSignalStuff(skb, stats, desc, driver_info);
10033         }
10034 }
10035 #else
10036 void query_rxdesc_status(struct sk_buff *skb, struct ieee80211_rx_stats *stats, bool bIsRxAggrSubframe)
10037 {
10038         rtl8192_rx_info *info = (struct rtl8192_rx_info *)skb->cb;
10039         struct net_device *dev=info->dev;
10040         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
10041         //rx_desc_819x_usb *desc = (rx_desc_819x_usb *)skb->data;
10042         rx_drvinfo_819x_usb  *driver_info = NULL;
10043
10044         //
10045         //Get Rx Descriptor Information
10046         //
10047         {
10048                 rx_desc_819x_usb *desc = (rx_desc_819x_usb *)skb->data;
10049
10050                 stats->Length = desc->Length;
10051                 stats->RxDrvInfoSize = desc->RxDrvInfoSize;
10052                 stats->RxBufShift = 0;//desc->Shift&0x03;
10053                 stats->bICV = desc->ICV;
10054                 stats->bCRC = desc->CRC32;
10055                 stats->bHwError = stats->bCRC|stats->bICV;
10056                 //RTL8190 set this bit to indicate that Hw does not decrypt packet
10057                 stats->Decrypted = !desc->SWDec;
10058         }
10059
10060         if((priv->ieee80211->pHTInfo->bCurrentHTSupport == true) && (priv->ieee80211->pairwise_key_type == KEY_TYPE_CCMP))
10061         {
10062                 stats->bHwError = false;
10063         }
10064         else
10065         {
10066                 stats->bHwError = stats->bCRC|stats->bICV;
10067         }
10068
10069         if(stats->Length < 24 || stats->Length > MAX_8192U_RX_SIZE)
10070                 stats->bHwError |= 1;
10071         //
10072         //Get Driver Info
10073         //
10074         // TODO: Need to verify it on FGPA platform
10075         //Driver info are written to the RxBuffer following rx desc
10076         if (stats->RxDrvInfoSize != 0) {
10077                 driver_info = (rx_drvinfo_819x_usb *)(skb->data + sizeof(rx_desc_819x_usb) + \
10078                                 stats->RxBufShift);
10079                 /* unit: 0.5M */
10080                 /* TODO */
10081                 if(!stats->bHwError){
10082                         u8      ret_rate;
10083                         ret_rate = HwRateToMRate90(driver_info->RxHT, driver_info->RxRate);
10084                         if(ret_rate == 0xff)
10085                         {
10086                                 // Abnormal Case: Receive CRC OK packet with Rx descriptor indicating non supported rate.
10087                                 // Special Error Handling here, 2008.05.16, by Emily
10088
10089                                 stats->bHwError = 1;
10090                                 stats->rate = MGN_1M;   //Set 1M rate by default
10091                         }else
10092                         {
10093                                 stats->rate = ret_rate;
10094                         }
10095                 }
10096                 else
10097                         stats->rate = 0x02;
10098
10099                 stats->bShortPreamble = driver_info->SPLCP;
10100
10101
10102                 UpdateReceivedRateHistogramStatistics8190(dev, stats);
10103
10104                 stats->bIsAMPDU = (driver_info->PartAggr==1);
10105                 stats->bFirstMPDU = (driver_info->PartAggr==1) && (driver_info->FirstAGGR==1);
10106 #if 0
10107                 // TODO: it is debug only. It should be disabled in released driver. 2007.1.12 by Joseph
10108                 UpdateRxAMPDUHistogramStatistics8190(Adapter, pRfd);
10109 #endif
10110                 stats->TimeStampLow = driver_info->TSFL;
10111                 // xiong mask it, 070514
10112                 //pRfd->Status.TimeStampHigh = PlatformEFIORead4Byte(Adapter, TSFR+4);
10113                 // stats->TimeStampHigh = read_nic_dword(dev,  TSFR+4);
10114
10115                 UpdateRxPktTimeStamp8190(dev, stats);
10116
10117                 //
10118                 // Rx A-MPDU
10119                 //
10120                 if(driver_info->FirstAGGR==1 || driver_info->PartAggr == 1)
10121                         RT_TRACE(COMP_RXDESC, "driver_info->FirstAGGR = %d, driver_info->PartAggr = %d\n",
10122                                         driver_info->FirstAGGR, driver_info->PartAggr);
10123
10124         }
10125
10126         skb_pull(skb,sizeof(rx_desc_819x_usb));
10127         //
10128         // Get Total offset of MPDU Frame Body
10129         //
10130         if((stats->RxBufShift + stats->RxDrvInfoSize) > 0) {
10131                 stats->bShift = 1;
10132                 skb_pull(skb,stats->RxBufShift + stats->RxDrvInfoSize);
10133         }
10134
10135         /* for debug 2008.5.29 */
10136 #if 0
10137         {
10138                 int i;
10139                 printk("\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
10140                 for(i = 0; i < skb->len; i++) {
10141                         if(i % 10 == 0) printk("\n");
10142                         printk("%02x ", skb->data[i]);
10143                 }
10144                 printk("\n<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
10145         }
10146 #endif
10147
10148         //added by vivi, for MP, 20080108
10149         stats->RxIs40MHzPacket = driver_info->BW;
10150         if(stats->RxDrvInfoSize != 0)
10151                 TranslateRxSignalStuff819xUsb(skb, stats, driver_info);
10152
10153 }
10154 #endif
10155
10156 #ifdef RTL8192SU
10157 #if 0
10158 /*-----------------------------------------------------------------------------
10159  * Function:    UpdateRxAMPDUHistogramStatistics8192S
10160  *
10161  * Overview:    Recored down the received A-MPDU aggregation size and pkt number
10162  *
10163  * Input:       Adapter
10164  *
10165  * Output:      Adapter
10166  *                              (Adapter->RxStats.RxAMPDUSizeHistogram[] is updated)
10167  *                              (Adapter->RxStats.RxAMPDUNumHistogram[] is updated)
10168  *
10169  * Return:      NONE
10170  *
10171  * Revised History:
10172  * When                 Who             Remark
10173  * 09/18/2008   MHC             Create Version 0.
10174  *
10175  *---------------------------------------------------------------------------*/
10176 static  void
10177 UpdateRxAMPDUHistogramStatistics8192S(
10178         struct net_device *dev,
10179         struct ieee80211_rx_stats *stats
10180         )
10181 {
10182         //HAL_DATA_TYPE                 *pHalData = GET_HAL_DATA(Adapter);
10183         u8      size_index;
10184         u8      num_index;
10185         u16     update_size = 0;
10186         u8      update_num = 0;
10187
10188         if(stats->bIsAMPDU)
10189         {
10190                 if(stats->bFirstMPDU)
10191                 {
10192                         if(stats->nRxAMPDU_Size!=0 && stats->nRxAMPDU_AggrNum!=0)
10193                         {
10194                                 update_size = stats->nRxAMPDU_Size;
10195                                 update_num = stats->nRxAMPDU_AggrNum;
10196                         }
10197                         stats->nRxAMPDU_Size = stats->Length;
10198                         stats->nRxAMPDU_AggrNum = 1;
10199                 }
10200                 else
10201                 {
10202                         stats->nRxAMPDU_Size += stats->Length;
10203                         stats->nRxAMPDU_AggrNum++;
10204                 }
10205         }
10206         else
10207         {
10208                 if(stats->nRxAMPDU_Size!=0 && stats->nRxAMPDU_AggrNum!=0)
10209                 {
10210                         update_size = stats->nRxAMPDU_Size;
10211                         update_num = stats->nRxAMPDU_AggrNum;
10212                 }
10213                 stats->nRxAMPDU_Size = 0;
10214                 stats->nRxAMPDU_AggrNum = 0;
10215         }
10216
10217         if(update_size!=0 && update_num!= 0)
10218         {
10219                 if(update_size < 4096)
10220                         size_index = 0;
10221                 else if(update_size < 8192)
10222                         size_index = 1;
10223                 else if(update_size < 16384)
10224                         size_index = 2;
10225                 else if(update_size < 32768)
10226                         size_index = 3;
10227                 else if(update_size < 65536)
10228                         size_index = 4;
10229                 else
10230                 {
10231                         RT_TRACE(COMP_RXDESC,
10232                         ("UpdateRxAMPDUHistogramStatistics8192S(): A-MPDU too large\n");
10233                 }
10234
10235                 Adapter->RxStats.RxAMPDUSizeHistogram[size_index]++;
10236
10237                 if(update_num < 5)
10238                         num_index = 0;
10239                 else if(update_num < 10)
10240                         num_index = 1;
10241                 else if(update_num < 20)
10242                         num_index = 2;
10243                 else if(update_num < 40)
10244                         num_index = 3;
10245                 else
10246                         num_index = 4;
10247
10248                 Adapter->RxStats.RxAMPDUNumHistogram[num_index]++;
10249         }
10250 }       // UpdateRxAMPDUHistogramStatistics8192S
10251 #endif
10252
10253 #endif
10254
10255
10256 #ifdef RTL8192SU
10257 //
10258 // Description:
10259 //      The strarting address of wireless lan header will shift 1 or 2 or 3 or "more" bytes for the following reason :
10260 //      (1) QoS control : shift 2 bytes
10261 //      (2) Mesh Network : shift 1 or 3 bytes
10262 //      (3) RxDriverInfo occupies  the front parts of Rx Packets buffer(shift units is in 8Bytes)
10263 //
10264 //      It is because Lextra CPU used by 8186 or 865x series assert exception if the statrting address
10265 //      of IP header is not double word alignment.
10266 //      This features is supported in 818xb and 8190 only, but not 818x.
10267 //
10268 //      parameter: PRT_RFD, Pointer of Reeceive frame descriptor which is initialized according to
10269 //                                           Rx Descriptor
10270 //      return value: unsigned int,  number of total shifted bytes
10271 //
10272 //      Notes: 2008/06/28, created by Roger
10273 //
10274 u32 GetRxPacketShiftBytes8192SU(struct ieee80211_rx_stats  *Status, bool bIsRxAggrSubframe)
10275 {
10276         //PRT_RFD_STATUS        pRtRfdStatus = &pRfd->Status;
10277
10278         return (sizeof(rx_desc_819x_usb) + Status->RxDrvInfoSize + Status->RxBufShift);
10279 }
10280
10281 void rtl8192SU_rx_nomal(struct sk_buff* skb)
10282 {
10283         rtl8192_rx_info *info = (struct rtl8192_rx_info *)skb->cb;
10284         struct net_device *dev=info->dev;
10285         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
10286         struct ieee80211_rx_stats stats = {
10287                 .signal = 0,
10288                 .noise = -98,
10289                 .rate = 0,
10290                 //      .mac_time = jiffies,
10291                 .freq = IEEE80211_24GHZ_BAND,
10292         };
10293         u32 rx_pkt_len = 0;
10294         struct ieee80211_hdr_1addr *ieee80211_hdr = NULL;
10295         bool unicast_packet = false;
10296
10297         //printk("**********skb->len = %d\n", skb->len);
10298         /* 20 is for ps-poll */
10299         if((skb->len >=(20 + sizeof(rx_desc_819x_usb))) && (skb->len < RX_URB_SIZE)) {
10300
10301                 /* first packet should not contain Rx aggregation header */
10302                 rtl8192SU_query_rxdesc_status(skb, &stats, false);
10303                 /* TODO */
10304
10305                 /* hardware related info */
10306                 priv->stats.rxoktotal++;  //YJ,test,090108
10307
10308                 /* Process the MPDU recevied */
10309                 skb_trim(skb, skb->len - 4/*sCrcLng*/);//FIXLZM
10310
10311                 rx_pkt_len = skb->len;
10312                 ieee80211_hdr = (struct ieee80211_hdr_1addr *)skb->data;
10313                 unicast_packet = false;
10314                 if(is_broadcast_ether_addr(ieee80211_hdr->addr1)) {
10315                         //TODO
10316                 }else if(is_multicast_ether_addr(ieee80211_hdr->addr1)){
10317                         //TODO
10318                 }else {
10319                         /* unicast packet */
10320                         unicast_packet = true;
10321                 }
10322
10323                 if(!ieee80211_rx(priv->ieee80211,skb, &stats)) {
10324                         dev_kfree_skb_any(skb);
10325                 } else {
10326                 //      priv->stats.rxoktotal++;  //YJ,test,090108
10327                         if(unicast_packet) {
10328                                 priv->stats.rxbytesunicast += rx_pkt_len;
10329                         }
10330                 }
10331
10332                 //up is firs pkt, follow is next and next
10333         }
10334         else
10335         {
10336                 priv->stats.rxurberr++;
10337                 printk("actual_length:%d\n", skb->len);
10338                 dev_kfree_skb_any(skb);
10339         }
10340
10341 }
10342 #else
10343 u32 GetRxPacketShiftBytes819xUsb(struct ieee80211_rx_stats  *Status, bool bIsRxAggrSubframe)
10344 {
10345                 return (sizeof(rx_desc_819x_usb) + Status->RxDrvInfoSize
10346                                 + Status->RxBufShift);
10347 }
10348
10349 void rtl8192_rx_nomal(struct sk_buff* skb)
10350 {
10351         rtl8192_rx_info *info = (struct rtl8192_rx_info *)skb->cb;
10352         struct net_device *dev=info->dev;
10353         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
10354         struct ieee80211_rx_stats stats = {
10355                 .signal = 0,
10356                 .noise = -98,
10357                 .rate = 0,
10358                 //      .mac_time = jiffies,
10359                 .freq = IEEE80211_24GHZ_BAND,
10360         };
10361         u32 rx_pkt_len = 0;
10362         struct ieee80211_hdr_1addr *ieee80211_hdr = NULL;
10363         bool unicast_packet = false;
10364
10365         /* 20 is for ps-poll */
10366         if((skb->len >=(20 + sizeof(rx_desc_819x_usb))) && (skb->len < RX_URB_SIZE)) {
10367                 /* first packet should not contain Rx aggregation header */
10368                 query_rxdesc_status(skb, &stats, false);
10369                 /* TODO */
10370                 /* hardware related info */
10371                 /* Process the MPDU recevied */
10372                 skb_trim(skb, skb->len - 4/*sCrcLng*/);
10373
10374                 rx_pkt_len = skb->len;
10375                 ieee80211_hdr = (struct ieee80211_hdr_1addr *)skb->data;
10376                 unicast_packet = false;
10377                 if(is_broadcast_ether_addr(ieee80211_hdr->addr1)) {
10378                         //TODO
10379                 }else if(is_multicast_ether_addr(ieee80211_hdr->addr1)){
10380                         //TODO
10381                 }else {
10382                         /* unicast packet */
10383                         unicast_packet = true;
10384                 }
10385
10386                 if(!ieee80211_rx(priv->ieee80211,skb, &stats)) {
10387                         dev_kfree_skb_any(skb);
10388                 } else {
10389                         priv->stats.rxoktotal++;
10390                         if(unicast_packet) {
10391                                 priv->stats.rxbytesunicast += rx_pkt_len;
10392                         }
10393                 }
10394         } else {
10395                 priv->stats.rxurberr++;
10396                 printk("actual_length:%d\n", skb->len);
10397                 dev_kfree_skb_any(skb);
10398         }
10399
10400 }
10401
10402 #endif
10403
10404 void
10405 rtl819xusb_process_received_packet(
10406         struct net_device *dev,
10407         struct ieee80211_rx_stats *pstats
10408         )
10409 {
10410 //      bool bfreerfd=false, bqueued=false;
10411         u8*     frame;
10412         u16     frame_len=0;
10413         struct r8192_priv *priv = ieee80211_priv(dev);
10414 //      u8                      index = 0;
10415 //      u8                      TID = 0;
10416         //u16                   seqnum = 0;
10417         //PRX_TS_RECORD pts = NULL;
10418
10419         // Get shifted bytes of Starting address of 802.11 header. 2006.09.28, by Emily
10420         //porting by amy 080508
10421         pstats->virtual_address += get_rxpacket_shiftbytes_819xusb(pstats);
10422         frame = pstats->virtual_address;
10423         frame_len = pstats->packetlength;
10424 #ifdef TODO     // by amy about HCT
10425         if(!Adapter->bInHctTest)
10426                 CountRxErrStatistics(Adapter, pRfd);
10427 #endif
10428         {
10429         #ifdef ENABLE_PS  //by amy for adding ps function in future
10430                 RT_RF_POWER_STATE rtState;
10431                 // When RF is off, we should not count the packet for hw/sw synchronize
10432                 // reason, ie. there may be a duration while sw switch is changed and hw
10433                 // switch is being changed. 2006.12.04, by shien chang.
10434                 Adapter->HalFunc.GetHwRegHandler(Adapter, HW_VAR_RF_STATE, (u8* )(&rtState));
10435                 if (rtState == eRfOff)
10436                 {
10437                         return;
10438                 }
10439         #endif
10440         priv->stats.rxframgment++;
10441
10442         }
10443 #ifdef TODO
10444         RmMonitorSignalStrength(Adapter, pRfd);
10445 #endif
10446         /* 2007/01/16 MH Add RX command packet handle here. */
10447         /* 2007/03/01 MH We have to release RFD and return if rx pkt is cmd pkt. */
10448         if (rtl819xusb_rx_command_packet(dev, pstats))
10449         {
10450                 return;
10451         }
10452
10453 #ifdef SW_CRC_CHECK
10454         SwCrcCheck();
10455 #endif
10456
10457
10458 }
10459
10460 void query_rx_cmdpkt_desc_status(struct sk_buff *skb, struct ieee80211_rx_stats *stats)
10461 {
10462 //      rtl8192_rx_info *info = (struct rtl8192_rx_info *)skb->cb;
10463 //      struct net_device *dev=info->dev;
10464 //      struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
10465         rx_desc_819x_usb *desc = (rx_desc_819x_usb *)skb->data;
10466 //      rx_drvinfo_819x_usb  *driver_info;
10467
10468         //
10469         //Get Rx Descriptor Information
10470         //
10471         stats->virtual_address = (u8*)skb->data;
10472         stats->Length = desc->Length;
10473         stats->RxDrvInfoSize = 0;
10474         stats->RxBufShift = 0;
10475         stats->packetlength = stats->Length-scrclng;
10476         stats->fraglength = stats->packetlength;
10477         stats->fragoffset = 0;
10478         stats->ntotalfrag = 1;
10479 }
10480
10481 #ifdef RTL8192SU
10482 void rtl8192SU_rx_cmd(struct sk_buff *skb)
10483 {
10484         struct rtl8192_rx_info *info = (struct rtl8192_rx_info *)skb->cb;
10485         struct net_device *dev = info->dev;
10486
10487         /* TODO */
10488         struct ieee80211_rx_stats stats = {
10489                 .signal = 0,
10490                 .noise = -98,
10491                 .rate = 0,
10492                 //      .mac_time = jiffies,
10493                 .freq = IEEE80211_24GHZ_BAND,
10494         };
10495
10496         //
10497         // Check buffer length to determine if this is a valid MPDU.
10498         //
10499         if( (skb->len >= sizeof(rx_desc_819x_usb)) && (skb->len <= RX_URB_SIZE) )//&&
10500                 //(pHalData->SwChnlInProgress == FALSE))
10501         {
10502                 //
10503                 // Collection information in Rx descriptor.
10504                 //
10505 #if 0
10506                 pRxDesc = pContext->Buffer;
10507
10508                 pRfd->Buffer.VirtualAddress = pContext->Buffer; // 061109, rcnjko, for multi-platform consideration..
10509
10510                 pRtRfdStatus->Length = (u2Byte)GET_RX_DESC_PKT_LEN(pRxDesc);
10511                 pRtRfdStatus->RxDrvInfoSize = 0;
10512                 pRtRfdStatus->RxBufShift = 0;
10513
10514                 pRfd->PacketLength      = pRfd->Status.Length - sCrcLng;
10515                 pRfd->FragLength        = pRfd->PacketLength;
10516                 pRfd->FragOffset        = 0;
10517                 pRfd->nTotalFrag        = 1;
10518                 pRfd->queue_id = PipeIndex;
10519 #endif
10520                 query_rx_cmdpkt_desc_status(skb,&stats);
10521                 // this is to be done by amy 080508     prfd->queue_id = 1;
10522
10523                 //
10524                 // Process the MPDU recevied.
10525                 //
10526                 rtl819xusb_process_received_packet(dev,&stats);
10527
10528                 dev_kfree_skb_any(skb);
10529         }
10530         else
10531         {
10532                 //RTInsertTailListWithCnt(&pAdapter->RfdIdleQueue, &pRfd->List, &pAdapter->NumIdleRfd);
10533                 //RT_ASSERT(pAdapter->NumIdleRfd <= pAdapter->NumRfd, ("HalUsbInCommandComplete8192SUsb(): Adapter->NumIdleRfd(%d)\n", pAdapter->NumIdleRfd));
10534                 //RT_TRACE(COMP_RECV, DBG_LOUD, ("HalUsbInCommandComplete8192SUsb(): NOT enough Resources!! BufLenUsed(%d), NumIdleRfd(%d)\n",
10535                         //pContext->BufLenUsed, pAdapter->NumIdleRfd));
10536         }
10537
10538         //
10539         // Reuse USB_IN_CONTEXT since we had finished processing the
10540         // buffer in USB_IN_CONTEXT.
10541         //
10542         //HalUsbReturnInContext(pAdapter, pContext);
10543
10544         //
10545         // Issue another bulk IN transfer.
10546         //
10547         //HalUsbInMpdu(pAdapter, PipeIndex);
10548
10549         RT_TRACE(COMP_RECV, "<--- HalUsbInCommandComplete8192SUsb()\n");
10550
10551 }
10552 #else
10553 void rtl8192_rx_cmd(struct sk_buff *skb)
10554 {
10555         struct rtl8192_rx_info *info = (struct rtl8192_rx_info *)skb->cb;
10556         struct net_device *dev = info->dev;
10557         //int ret;
10558 //      struct urb *rx_urb = info->urb;
10559         /* TODO */
10560         struct ieee80211_rx_stats stats = {
10561                 .signal = 0,
10562                 .noise = -98,
10563                 .rate = 0,
10564                 //      .mac_time = jiffies,
10565                 .freq = IEEE80211_24GHZ_BAND,
10566         };
10567
10568         if((skb->len >=(20 + sizeof(rx_desc_819x_usb))) && (skb->len < RX_URB_SIZE))
10569         {
10570
10571                 query_rx_cmdpkt_desc_status(skb,&stats);
10572                 // this is to be done by amy 080508     prfd->queue_id = 1;
10573
10574
10575                 //
10576                 //  Process the command packet received.
10577                 //
10578
10579                 rtl819xusb_process_received_packet(dev,&stats);
10580
10581                 dev_kfree_skb_any(skb);
10582         }
10583         else
10584                 ;
10585
10586
10587 #if 0
10588         desc = (u32*)(skb->data);
10589         cmd = (desc[0] >> 30) & 0x03;
10590
10591         if(cmd == 0x00) {//beacon interrupt
10592                 //send beacon packet
10593                 skb = ieee80211_get_beacon(priv->ieee80211);
10594
10595                 if(!skb){
10596                         DMESG("not enought memory for allocating beacon");
10597                         return;
10598                 }
10599                 skb->cb[0] = BEACON_PRIORITY;
10600                 skb->cb[1] = 0;
10601                 skb->cb[2] = ieeerate2rtlrate(priv->ieee80211->basic_rate);
10602                 ret = rtl8192_tx(dev, skb);
10603
10604                 if( ret != 0 ){
10605                         printk(KERN_ALERT "tx beacon packet error : %d !\n", ret);
10606                 }
10607                 dev_kfree_skb_any(skb);
10608         } else {//0x00
10609                 //{ log the device information
10610                 // At present, It is not implemented just now.
10611                 //}
10612         }
10613 #endif
10614 }
10615 #endif
10616
10617 void rtl8192_irq_rx_tasklet(struct r8192_priv *priv)
10618 {
10619         struct sk_buff *skb;
10620         struct rtl8192_rx_info *info;
10621
10622         while (NULL != (skb = skb_dequeue(&priv->skb_queue))) {
10623                 info = (struct rtl8192_rx_info *)skb->cb;
10624                 switch (info->out_pipe) {
10625                 /* Nomal packet pipe */
10626                         case 3:
10627                                 //RT_TRACE(COMP_RECV, "normal in-pipe index(%d)\n",info->out_pipe);
10628                                 priv->IrpPendingCount--;
10629                                 priv->ops->rtl819x_rx_nomal(skb);
10630                                 break;
10631
10632                                 /* Command packet pipe */
10633                         case 9:
10634                                 RT_TRACE(COMP_RECV, "command in-pipe index(%d)\n",\
10635                                                 info->out_pipe);
10636                                 priv->ops->rtl819x_rx_cmd(skb);
10637                                 break;
10638
10639                         default: /* should never get here! */
10640                                 RT_TRACE(COMP_ERR, "Unknown in-pipe index(%d)\n",\
10641                                                 info->out_pipe);
10642                                 dev_kfree_skb(skb);
10643                                 break;
10644
10645                 }
10646         }
10647 }
10648
10649
10650
10651 /****************************************************************************
10652      ---------------------------- USB_STUFF---------------------------
10653 *****************************************************************************/
10654 //LZM Merge from windows HalUsbSetQueuePipeMapping8192SUsb 090319
10655 static void HalUsbSetQueuePipeMapping8192SUsb(struct usb_interface *intf, struct net_device *dev)
10656 {
10657         struct r8192_priv *priv = ieee80211_priv(dev);
10658         struct usb_host_interface *iface_desc;
10659         struct usb_endpoint_descriptor *endpoint;
10660         u8 i = 0;
10661
10662         priv->ep_in_num = 0;
10663         priv->ep_out_num = 0;
10664         memset(priv->RtOutPipes,0,16);
10665         memset(priv->RtInPipes,0,16);
10666
10667         iface_desc = intf->cur_altsetting;
10668         priv->ep_num = iface_desc->desc.bNumEndpoints;
10669
10670         for (i = 0; i < priv->ep_num; ++i) {
10671                 endpoint = &iface_desc->endpoint[i].desc;
10672                 if (usb_endpoint_is_bulk_in(endpoint)) {
10673                         priv->RtInPipes[priv->ep_in_num] = usb_endpoint_num(endpoint);
10674                         priv->ep_in_num ++;
10675                         //printk("in_endpoint_idx = %d\n", usb_endpoint_num(endpoint));
10676                 } else if (usb_endpoint_is_bulk_out(endpoint)) {
10677                         priv->RtOutPipes[priv->ep_out_num] = usb_endpoint_num(endpoint);
10678                         priv->ep_out_num ++;
10679                         //printk("out_endpoint_idx = %d\n", usb_endpoint_num(endpoint));
10680                 }
10681         }
10682         {
10683                 memset(priv->txqueue_to_outpipemap,0,9);
10684                 if (priv->ep_num == 6) {
10685                         // BK, BE, VI, VO, HCCA, TXCMD, MGNT, HIGH, BEACON
10686                         u8 queuetopipe[] = {3, 2, 1, 0, 4, 4, 4, 4, 4};
10687
10688                         memcpy(priv->txqueue_to_outpipemap,queuetopipe,9);
10689                 } else if (priv->ep_num == 4) {
10690                         // BK, BE, VI, VO, HCCA, TXCMD, MGNT, HIGH, BEACON
10691                         u8 queuetopipe[] = {1, 1, 0, 0, 2, 2, 2, 2, 2};
10692
10693                         memcpy(priv->txqueue_to_outpipemap,queuetopipe,9);
10694                 } else if (priv->ep_num > 9) {
10695                         // BK, BE, VI, VO, HCCA, TXCMD, MGNT, HIGH, BEACON
10696                         u8 queuetopipe[] = {3, 2, 1, 0, 4, 8, 7, 6, 5};
10697
10698                         memcpy(priv->txqueue_to_outpipemap,queuetopipe,9);
10699                 } else {//use sigle pipe
10700                         // BK, BE, VI, VO, HCCA, TXCMD, MGNT, HIGH, BEACON
10701                         u8 queuetopipe[] = {0, 0, 0, 0, 0, 0, 0, 0, 0};
10702                         memcpy(priv->txqueue_to_outpipemap,queuetopipe,9);
10703                 }
10704         }
10705         printk("==>ep_num:%d, in_ep_num:%d, out_ep_num:%d\n", priv->ep_num, priv->ep_in_num, priv->ep_out_num);
10706
10707         printk("==>RtInPipes:");
10708         for(i=0; i < priv->ep_in_num; i++)
10709                 printk("%d  ", priv->RtInPipes[i]);
10710         printk("\n");
10711
10712         printk("==>RtOutPipes:");
10713         for(i=0; i < priv->ep_out_num; i++)
10714                 printk("%d  ", priv->RtOutPipes[i]);
10715         printk("\n");
10716
10717         printk("==>txqueue_to_outpipemap for BK, BE, VI, VO, HCCA, TXCMD, MGNT, HIGH, BEACON:\n");
10718         for(i=0; i < 9; i++)
10719                 printk("%d  ", priv->txqueue_to_outpipemap[i]);
10720         printk("\n");
10721
10722         return;
10723 }
10724
10725 static const struct net_device_ops rtl8192_netdev_ops = {
10726         .ndo_open               = rtl8192_open,
10727         .ndo_stop               = rtl8192_close,
10728         .ndo_get_stats          = rtl8192_stats,
10729         .ndo_tx_timeout         = tx_timeout,
10730         .ndo_do_ioctl           = rtl8192_ioctl,
10731         .ndo_set_multicast_list = r8192_set_multicast,
10732         .ndo_set_mac_address    = r8192_set_mac_adr,
10733         .ndo_validate_addr      = eth_validate_addr,
10734         .ndo_change_mtu         = eth_change_mtu,
10735         .ndo_start_xmit         = rtl8192_ieee80211_xmit,
10736 };
10737
10738 static int __devinit rtl8192_usb_probe(struct usb_interface *intf,
10739                          const struct usb_device_id *id)
10740 {
10741 //      unsigned long ioaddr = 0;
10742         struct net_device *dev = NULL;
10743         struct r8192_priv *priv= NULL;
10744         struct usb_device *udev = interface_to_usbdev(intf);
10745
10746         RT_TRACE(COMP_INIT, "Oops: i'm coming\n");
10747
10748         dev = alloc_ieee80211(sizeof(struct r8192_priv));
10749
10750         usb_set_intfdata(intf, dev);
10751         SET_NETDEV_DEV(dev, &intf->dev);
10752         priv = ieee80211_priv(dev);
10753         priv->ieee80211 = netdev_priv(dev);
10754         priv->udev=udev;
10755
10756 #ifdef RTL8192SU
10757         HalUsbSetQueuePipeMapping8192SUsb(intf, dev);
10758 #endif
10759
10760 #ifdef RTL8192SU
10761         //printk("===============>NIC 8192SU\n");
10762         priv->ops = &rtl8192su_ops;
10763 #else
10764         //printk("===============>NIC 8192U\n");
10765         priv->ops = &rtl8192u_ops;
10766 #endif
10767
10768         dev->netdev_ops = &rtl8192_netdev_ops;
10769
10770          //DMESG("Oops: i'm coming\n");
10771         dev->wireless_handlers = (struct iw_handler_def *) &r8192_wx_handlers_def;
10772
10773         dev->type=ARPHRD_ETHER;
10774
10775         dev->watchdog_timeo = HZ*3;     //modified by john, 0805
10776
10777         if (dev_alloc_name(dev, ifname) < 0){
10778                 RT_TRACE(COMP_INIT, "Oops: devname already taken! Trying wlan%%d...\n");
10779                 ifname = "wlan%d";
10780                 dev_alloc_name(dev, ifname);
10781         }
10782
10783         RT_TRACE(COMP_INIT, "Driver probe completed1\n");
10784 #if 1
10785         if(rtl8192_init(dev)!=0){
10786                 RT_TRACE(COMP_ERR, "Initialization failed");
10787                 goto fail;
10788         }
10789 #endif
10790         netif_carrier_off(dev);
10791         netif_stop_queue(dev);
10792
10793         register_netdev(dev);
10794         RT_TRACE(COMP_INIT, "dev name=======> %s\n",dev->name);
10795         rtl8192_proc_init_one(dev);
10796
10797
10798         RT_TRACE(COMP_INIT, "Driver probe completed\n");
10799         return 0;
10800 fail:
10801         free_ieee80211(dev);
10802
10803         RT_TRACE(COMP_ERR, "wlan driver load failed\n");
10804         return -ENODEV;
10805 }
10806
10807 //detach all the work and timer structure declared or inititialize in r8192U_init function.
10808 void rtl8192_cancel_deferred_work(struct r8192_priv* priv)
10809 {
10810         cancel_work_sync(&priv->reset_wq);
10811         cancel_work_sync(&priv->qos_activate);
10812         cancel_delayed_work(&priv->watch_dog_wq);
10813         cancel_delayed_work(&priv->update_beacon_wq);
10814         cancel_delayed_work(&priv->ieee80211->hw_wakeup_wq);
10815         cancel_delayed_work(&priv->ieee80211->hw_sleep_wq);
10816         //cancel_work_sync(&priv->SetBWModeWorkItem);
10817         //cancel_work_sync(&priv->SwChnlWorkItem);
10818 }
10819
10820 static void __devexit rtl8192_usb_disconnect(struct usb_interface *intf)
10821 {
10822         struct net_device *dev = usb_get_intfdata(intf);
10823         struct r8192_priv *priv = ieee80211_priv(dev);
10824         if(dev){
10825
10826                 unregister_netdev(dev);
10827
10828                 RT_TRACE(COMP_DOWN, "=============>wlan driver to be removed\n");
10829                 rtl8192_proc_remove_one(dev);
10830
10831                         rtl8192_down(dev);
10832                 if (priv->pFirmware)
10833                 {
10834                         vfree(priv->pFirmware);
10835                         priv->pFirmware = NULL;
10836                 }
10837         //      priv->rf_close(dev);
10838 //              rtl8192_SetRFPowerState(dev, eRfOff);
10839                 destroy_workqueue(priv->priv_wq);
10840                 //rtl8192_irq_disable(dev);
10841                 //rtl8192_reset(dev);
10842                 mdelay(10);
10843
10844         }
10845         free_ieee80211(dev);
10846         RT_TRACE(COMP_DOWN, "wlan driver removed\n");
10847 }
10848
10849 static int __init rtl8192_usb_module_init(void)
10850 {
10851         printk(KERN_INFO "\nLinux kernel driver for RTL8192 based WLAN cards\n");
10852         printk(KERN_INFO "Copyright (c) 2007-2008, Realsil Wlan\n");
10853         RT_TRACE(COMP_INIT, "Initializing module");
10854         RT_TRACE(COMP_INIT, "Wireless extensions version %d", WIRELESS_EXT);
10855         rtl8192_proc_module_init();
10856         return usb_register(&rtl8192_usb_driver);
10857 }
10858
10859
10860 static void __exit rtl8192_usb_module_exit(void)
10861 {
10862         usb_deregister(&rtl8192_usb_driver);
10863
10864         RT_TRACE(COMP_DOWN, "Exiting");
10865         rtl8192_proc_module_remove();
10866 }
10867
10868
10869 void rtl8192_try_wake_queue(struct net_device *dev, int pri)
10870 {
10871         unsigned long flags;
10872         short enough_desc;
10873         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
10874
10875         spin_lock_irqsave(&priv->tx_lock,flags);
10876         enough_desc = check_nic_enough_desc(dev,pri);
10877         spin_unlock_irqrestore(&priv->tx_lock,flags);
10878
10879         if(enough_desc)
10880                 ieee80211_wake_queue(priv->ieee80211);
10881 }
10882
10883 #if 0
10884 void DisableHWSecurityConfig8192SUsb(struct net_device *dev)
10885 {
10886         u8 SECR_value = 0x0;
10887         write_nic_byte(dev, SECR,  SECR_value);//SECR_value |  SCR_UseDK );
10888 }
10889 #endif
10890
10891 void EnableHWSecurityConfig8192(struct net_device *dev)
10892 {
10893         u8 SECR_value = 0x0;
10894         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
10895          struct ieee80211_device* ieee = priv->ieee80211;
10896
10897         SECR_value = SCR_TxEncEnable | SCR_RxDecEnable;
10898 #if 1
10899         if (((KEY_TYPE_WEP40 == ieee->pairwise_key_type) || (KEY_TYPE_WEP104 == ieee->pairwise_key_type)) && (priv->ieee80211->auth_mode != 2))
10900         {
10901                 SECR_value |= SCR_RxUseDK;
10902                 SECR_value |= SCR_TxUseDK;
10903         }
10904         else if ((ieee->iw_mode == IW_MODE_ADHOC) && (ieee->pairwise_key_type & (KEY_TYPE_CCMP | KEY_TYPE_TKIP)))
10905         {
10906                 SECR_value |= SCR_RxUseDK;
10907                 SECR_value |= SCR_TxUseDK;
10908         }
10909 #endif
10910         //add HWSec active enable here.
10911 //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
10912
10913         ieee->hwsec_active = 1;
10914
10915         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
10916         {
10917                 ieee->hwsec_active = 0;
10918                 SECR_value &= ~SCR_RxDecEnable;
10919         }
10920
10921         RT_TRACE(COMP_SEC,"%s:, hwsec:%d, pairwise_key:%d, SECR_value:%x\n", __FUNCTION__, \
10922                         ieee->hwsec_active, ieee->pairwise_key_type, SECR_value);
10923         {
10924                 write_nic_byte(dev, SECR,  SECR_value);//SECR_value |  SCR_UseDK );
10925         }
10926 }
10927
10928
10929 void setKey(    struct net_device *dev,
10930                 u8 EntryNo,
10931                 u8 KeyIndex,
10932                 u16 KeyType,
10933                 u8 *MacAddr,
10934                 u8 DefaultKey,
10935                 u32 *KeyContent )
10936 {
10937         u32 TargetCommand = 0;
10938         u32 TargetContent = 0;
10939         u16 usConfig = 0;
10940         u8 i;
10941         if (EntryNo >= TOTAL_CAM_ENTRY)
10942                 RT_TRACE(COMP_ERR, "cam entry exceeds in setKey()\n");
10943
10944         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));
10945
10946         if (DefaultKey)
10947                 usConfig |= BIT15 | (KeyType<<2);
10948         else
10949                 usConfig |= BIT15 | (KeyType<<2) | KeyIndex;
10950 //      usConfig |= BIT15 | (KeyType<<2) | (DefaultKey<<5) | KeyIndex;
10951
10952
10953         for(i=0 ; i<CAM_CONTENT_COUNT; i++){
10954                 TargetCommand  = i+CAM_CONTENT_COUNT*EntryNo;
10955                 TargetCommand |= BIT31|BIT16;
10956
10957                 if(i==0){//MAC|Config
10958                         TargetContent = (u32)(*(MacAddr+0)) << 16|
10959                                         (u32)(*(MacAddr+1)) << 24|
10960                                         (u32)usConfig;
10961
10962                         write_nic_dword(dev, WCAMI, TargetContent);
10963                         write_nic_dword(dev, RWCAM, TargetCommand);
10964         //              printk("setkey cam =%8x\n", read_cam(dev, i+6*EntryNo));
10965                 }
10966                 else if(i==1){//MAC
10967                         TargetContent = (u32)(*(MacAddr+2))      |
10968                                         (u32)(*(MacAddr+3)) <<  8|
10969                                         (u32)(*(MacAddr+4)) << 16|
10970                                         (u32)(*(MacAddr+5)) << 24;
10971                         write_nic_dword(dev, WCAMI, TargetContent);
10972                         write_nic_dword(dev, RWCAM, TargetCommand);
10973                 }
10974                 else {
10975                         //Key Material
10976                         if(KeyContent !=NULL){
10977                         write_nic_dword(dev, WCAMI, (u32)(*(KeyContent+i-2)) );
10978                         write_nic_dword(dev, RWCAM, TargetCommand);
10979                 }
10980         }
10981         }
10982
10983 }
10984
10985 /***************************************************************************
10986      ------------------- module init / exit stubs ----------------
10987 ****************************************************************************/
10988 module_init(rtl8192_usb_module_init);
10989 module_exit(rtl8192_usb_module_exit);