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