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