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