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