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