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