staging: rtl8192u: fix checkpatch.pl issues to line 514
[pandora-kernel.git] / drivers / staging / rtl8192u / 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_hw.h"
63 #include "r8192U.h"
64 #include "r8190_rtl8256.h" /* RTL8225 Radio frontend */
65 #include "r8180_93cx6.h"   /* Card EEPROM */
66 #include "r8192U_wx.h"
67 #include "r819xU_phy.h" //added by WB 4.30.2008
68 #include "r819xU_phyreg.h"
69 #include "r819xU_cmdpkt.h"
70 #include "r8192U_dm.h"
71 //#include "r8192xU_phyreg.h"
72 #include <linux/usb.h>
73 #include <linux/slab.h>
74 // FIXME: check if 2.6.7 is ok
75
76 #ifdef CONFIG_RTL8192_PM
77 #include "r8192_pm.h"
78 #endif
79
80 #ifdef ENABLE_DOT11D
81 #include "dot11d.h"
82 #endif
83 //set here to open your trace code. //WB
84 u32 rt_global_debug_component = \
85                         //      COMP_INIT       |
86 //                              COMP_DBG        |
87                         //      COMP_EPROM      |
88 //                              COMP_PHY        |
89                         //      COMP_RF         |
90 //                              COMP_FIRMWARE   |
91 //                              COMP_CH         |
92                         //      COMP_POWER_TRACKING |
93 //                              COMP_RATE       |
94                         //      COMP_TXAGC      |
95                 //              COMP_TRACE      |
96                                 COMP_DOWN       |
97                 //              COMP_RECV       |
98                 //              COMP_SWBW       |
99                                 COMP_SEC        |
100         //                      COMP_RESET      |
101                 //              COMP_SEND       |
102                         //      COMP_EVENTS     |
103                                 COMP_ERR ; //always open err flags on
104
105 #define TOTAL_CAM_ENTRY 32
106 #define CAM_CONTENT_COUNT 8
107
108 static const struct usb_device_id rtl8192_usb_id_tbl[] = {
109         /* Realtek */
110         {USB_DEVICE(0x0bda, 0x8192)},
111         {USB_DEVICE(0x0bda, 0x8709)},
112         /* Corega */
113         {USB_DEVICE(0x07aa, 0x0043)},
114         /* Belkin */
115         {USB_DEVICE(0x050d, 0x805E)},
116         /* Sitecom */
117         {USB_DEVICE(0x0df6, 0x0031)},
118         /* EnGenius */
119         {USB_DEVICE(0x1740, 0x9201)},
120         /* Dlink */
121         {USB_DEVICE(0x2001, 0x3301)},
122         /* Zinwell */
123         {USB_DEVICE(0x5a57, 0x0290)},
124         {}
125 };
126
127 MODULE_LICENSE("GPL");
128 MODULE_VERSION("V 1.1");
129 MODULE_DEVICE_TABLE(usb, rtl8192_usb_id_tbl);
130 MODULE_DESCRIPTION("Linux driver for Realtek RTL8192 USB WiFi cards");
131
132 static char* ifname = "wlan%d";
133 static int hwwep = 1;  //default use hw. set 0 to use software security
134 static int channels = 0x3fff;
135
136
137
138 module_param(ifname, charp, S_IRUGO|S_IWUSR );
139 //module_param(hwseqnum,int, S_IRUGO|S_IWUSR);
140 module_param(hwwep,int, S_IRUGO|S_IWUSR);
141 module_param(channels,int, S_IRUGO|S_IWUSR);
142
143 MODULE_PARM_DESC(ifname," Net interface name, wlan%d=default");
144 //MODULE_PARM_DESC(hwseqnum," Try to use hardware 802.11 header sequence numbers. Zero=default");
145 MODULE_PARM_DESC(hwwep," Try to use hardware security support. ");
146 MODULE_PARM_DESC(channels," Channel bitmask for specific locales. NYI");
147
148 static int __devinit rtl8192_usb_probe(struct usb_interface *intf,
149                          const struct usb_device_id *id);
150 static void __devexit rtl8192_usb_disconnect(struct usb_interface *intf);
151
152
153 static struct usb_driver rtl8192_usb_driver = {
154         .name           = RTL819xU_MODULE_NAME,           /* Driver name   */
155         .id_table       = rtl8192_usb_id_tbl,             /* PCI_ID table  */
156         .probe          = rtl8192_usb_probe,              /* probe fn      */
157         .disconnect     = rtl8192_usb_disconnect,         /* remove fn     */
158 #ifdef CONFIG_RTL8192_PM
159         .suspend        = rtl8192_suspend,                /* PM suspend fn */
160         .resume         = rtl8192_resume,                 /* PM resume fn  */
161 #else
162         .suspend        = NULL,                           /* PM suspend fn */
163         .resume         = NULL,                           /* PM resume fn  */
164 #endif
165 };
166
167 #ifdef ENABLE_DOT11D
168
169 typedef struct _CHANNEL_LIST
170 {
171         u8      Channel[32];
172         u8      Len;
173 }CHANNEL_LIST, *PCHANNEL_LIST;
174
175 static CHANNEL_LIST ChannelPlan[] = {
176         {{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
177         {{1,2,3,4,5,6,7,8,9,10,11},11},                                                 //IC
178         {{1,2,3,4,5,6,7,8,9,10,11,12,13,36,40,44,48,52,56,60,64},21},   //ETSI
179         {{1,2,3,4,5,6,7,8,9,10,11,12,13},13},    //Spain. Change to ETSI.
180         {{1,2,3,4,5,6,7,8,9,10,11,12,13},13},   //France. Change to ETSI.
181         {{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
182         {{1,2,3,4,5,6,7,8,9,10,11,12,13,14,36,40,44,48,52,56,60,64},22},//MKK1
183         {{1,2,3,4,5,6,7,8,9,10,11,12,13},13},   //Israel.
184         {{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
185         {{1,2,3,4,5,6,7,8,9,10,11,12,13,14,36,40,44,48,52,56,60,64}, 22},    //MIC
186         {{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
187 };
188
189 static void rtl819x_set_channel_map(u8 channel_plan, struct r8192_priv* priv)
190 {
191         int i, max_chan=-1, min_chan=-1;
192         struct ieee80211_device* ieee = priv->ieee80211;
193         switch (channel_plan)
194         {
195                 case COUNTRY_CODE_FCC:
196                 case COUNTRY_CODE_IC:
197                 case COUNTRY_CODE_ETSI:
198                 case COUNTRY_CODE_SPAIN:
199                 case COUNTRY_CODE_FRANCE:
200                 case COUNTRY_CODE_MKK:
201                 case COUNTRY_CODE_MKK1:
202                 case COUNTRY_CODE_ISRAEL:
203                 case COUNTRY_CODE_TELEC:
204                 case COUNTRY_CODE_MIC:
205                 {
206                         Dot11d_Init(ieee);
207                         ieee->bGlobalDomain = false;
208                         //acturally 8225 & 8256 rf chip only support B,G,24N mode
209                         if ((priv->rf_chip == RF_8225) || (priv->rf_chip == RF_8256))
210                         {
211                                 min_chan = 1;
212                                 max_chan = 14;
213                         }
214                         else
215                         {
216                                 RT_TRACE(COMP_ERR, "unknown rf chip, can't set channel map in function:%s()\n", __FUNCTION__);
217                         }
218                         if (ChannelPlan[channel_plan].Len != 0){
219                                 // Clear old channel map
220                                 memset(GET_DOT11D_INFO(ieee)->channel_map, 0, sizeof(GET_DOT11D_INFO(ieee)->channel_map));
221                                 // Set new channel map
222                                 for (i=0;i<ChannelPlan[channel_plan].Len;i++)
223                                 {
224                                         if (ChannelPlan[channel_plan].Channel[i] < min_chan || ChannelPlan[channel_plan].Channel[i] > max_chan)
225                                         break;
226                                         GET_DOT11D_INFO(ieee)->channel_map[ChannelPlan[channel_plan].Channel[i]] = 1;
227                                 }
228                         }
229                         break;
230                 }
231                 case COUNTRY_CODE_GLOBAL_DOMAIN:
232                 {
233                         GET_DOT11D_INFO(ieee)->bEnabled = 0;//this flag enabled to follow 11d country IE setting, otherwise, it shall follow global domain settings.
234                         Dot11d_Reset(ieee);
235                         ieee->bGlobalDomain = true;
236                         break;
237                 }
238                 default:
239                         break;
240         }
241         return;
242 }
243 #endif
244
245 #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 )
246
247 #define         rx_hal_is_cck_rate(_pdrvinfo)\
248                         (_pdrvinfo->RxRate == DESC90_RATE1M ||\
249                         _pdrvinfo->RxRate == DESC90_RATE2M ||\
250                         _pdrvinfo->RxRate == DESC90_RATE5_5M ||\
251                         _pdrvinfo->RxRate == DESC90_RATE11M) &&\
252                         !_pdrvinfo->RxHT\
253
254
255 void CamResetAllEntry(struct net_device *dev)
256 {
257         u32 ulcommand = 0;
258         //2004/02/11  In static WEP, OID_ADD_KEY or OID_ADD_WEP are set before STA associate to AP.
259         // However, ResetKey is called on OID_802_11_INFRASTRUCTURE_MODE and MlmeAssociateRequest
260         // In this condition, Cam can not be reset because upper layer will not set this static key again.
261         //if(Adapter->EncAlgorithm == WEP_Encryption)
262         //      return;
263 //debug
264         //DbgPrint("========================================\n");
265         //DbgPrint("                            Call ResetAllEntry                                              \n");
266         //DbgPrint("========================================\n\n");
267         ulcommand |= BIT31|BIT30;
268         write_nic_dword(dev, RWCAM, ulcommand);
269
270 }
271
272
273 void write_cam(struct net_device *dev, u8 addr, u32 data)
274 {
275         write_nic_dword(dev, WCAMI, data);
276         write_nic_dword(dev, RWCAM, BIT31|BIT16|(addr&0xff) );
277 }
278
279 u32 read_cam(struct net_device *dev, u8 addr)
280 {
281         write_nic_dword(dev, RWCAM, 0x80000000|(addr&0xff) );
282         return read_nic_dword(dev, 0xa8);
283 }
284
285 void write_nic_byte_E(struct net_device *dev, int indx, u8 data)
286 {
287         int status;
288         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
289         struct usb_device *udev = priv->udev;
290
291         status = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
292                                RTL8187_REQ_SET_REGS, RTL8187_REQT_WRITE,
293                                indx|0xfe00, 0, &data, 1, HZ / 2);
294
295         if (status < 0)
296         {
297                 printk("write_nic_byte_E TimeOut! status:%d\n", status);
298         }
299 }
300
301 u8 read_nic_byte_E(struct net_device *dev, int indx)
302 {
303         int status;
304         u8 data;
305         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
306         struct usb_device *udev = priv->udev;
307
308         status = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0),
309                                RTL8187_REQ_GET_REGS, RTL8187_REQT_READ,
310                                indx|0xfe00, 0, &data, 1, HZ / 2);
311
312         if (status < 0)
313         {
314                 printk("read_nic_byte_E TimeOut! status:%d\n", status);
315         }
316
317         return data;
318 }
319 //as 92U has extend page from 4 to 16, so modify functions below.
320 void write_nic_byte(struct net_device *dev, int indx, u8 data)
321 {
322         int status;
323
324         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
325         struct usb_device *udev = priv->udev;
326
327         status = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
328                                RTL8187_REQ_SET_REGS, RTL8187_REQT_WRITE,
329                                (indx&0xff)|0xff00, (indx>>8)&0x0f, &data, 1, HZ / 2);
330
331         if (status < 0)
332         {
333                 printk("write_nic_byte TimeOut! status:%d\n", status);
334         }
335
336
337 }
338
339
340 void write_nic_word(struct net_device *dev, int indx, u16 data)
341 {
342
343         int status;
344
345         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
346         struct usb_device *udev = priv->udev;
347
348         status = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
349                                RTL8187_REQ_SET_REGS, RTL8187_REQT_WRITE,
350                                (indx&0xff)|0xff00, (indx>>8)&0x0f, &data, 2, HZ / 2);
351
352         if (status < 0)
353         {
354                 printk("write_nic_word TimeOut! status:%d\n", status);
355         }
356
357 }
358
359
360 void write_nic_dword(struct net_device *dev, int indx, u32 data)
361 {
362
363         int status;
364
365         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
366         struct usb_device *udev = priv->udev;
367
368         status = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
369                                RTL8187_REQ_SET_REGS, RTL8187_REQT_WRITE,
370                                (indx&0xff)|0xff00, (indx>>8)&0x0f, &data, 4, HZ / 2);
371
372
373         if (status < 0)
374         {
375                 printk("write_nic_dword TimeOut! status:%d\n", status);
376         }
377
378 }
379
380
381
382 u8 read_nic_byte(struct net_device *dev, int indx)
383 {
384         u8 data;
385         int status;
386         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
387         struct usb_device *udev = priv->udev;
388
389         status = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0),
390                                RTL8187_REQ_GET_REGS, RTL8187_REQT_READ,
391                                (indx&0xff)|0xff00, (indx>>8)&0x0f, &data, 1, HZ / 2);
392
393         if (status < 0)
394         {
395                 printk("read_nic_byte TimeOut! status:%d\n", status);
396         }
397
398         return data;
399 }
400
401
402
403 u16 read_nic_word(struct net_device *dev, int indx)
404 {
405         u16 data;
406         int status;
407         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
408         struct usb_device *udev = priv->udev;
409
410         status = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0),
411                                        RTL8187_REQ_GET_REGS, RTL8187_REQT_READ,
412                                        (indx&0xff)|0xff00, (indx>>8)&0x0f,
413                                                         &data, 2, HZ / 2);
414
415         if (status < 0)
416                 printk("read_nic_word TimeOut! status:%d\n", status);
417
418         return data;
419 }
420
421 u16 read_nic_word_E(struct net_device *dev, int indx)
422 {
423         u16 data;
424         int status;
425         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
426         struct usb_device *udev = priv->udev;
427
428         status = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0),
429                                RTL8187_REQ_GET_REGS, RTL8187_REQT_READ,
430                                        indx|0xfe00, 0, &data, 2, HZ / 2);
431
432         if (status < 0)
433                 printk("read_nic_word TimeOut! status:%d\n", status);
434
435         return data;
436 }
437
438 u32 read_nic_dword(struct net_device *dev, int indx)
439 {
440         u32 data;
441         int status;
442         /* int result; */
443
444         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
445         struct usb_device *udev = priv->udev;
446
447         status = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0),
448                                        RTL8187_REQ_GET_REGS, RTL8187_REQT_READ,
449                                         (indx&0xff)|0xff00, (indx>>8)&0x0f,
450                                                         &data, 4, HZ / 2);
451         /* if(0 != result) {
452          *      printk(KERN_WARNING "read size of data = %d\, date = %d\n",
453          *                                                       result, data);
454          * }
455          */
456
457         if (status < 0)
458                 printk("read_nic_dword TimeOut! status:%d\n", status);
459
460         return data;
461 }
462
463 /* u8 read_phy_cck(struct net_device *dev, u8 adr); */
464 /* u8 read_phy_ofdm(struct net_device *dev, u8 adr); */
465 /* this might still called in what was the PHY rtl8185/rtl8192 common code
466  * plans are to possibilty turn it again in one common code...
467  */
468 inline void force_pci_posting(struct net_device *dev)
469 {
470 }
471
472 static struct net_device_stats *rtl8192_stats(struct net_device *dev);
473 void rtl8192_commit(struct net_device *dev);
474 /* void rtl8192_restart(struct net_device *dev); */
475 void rtl8192_restart(struct work_struct *work);
476 /* void rtl8192_rq_tx_ack(struct work_struct *work); */
477 void watch_dog_timer_callback(unsigned long data);
478
479 /****************************************************************************
480  *   -----------------------------PROCFS STUFF-------------------------
481 *****************************************************************************
482  */
483
484 static struct proc_dir_entry *rtl8192_proc;
485
486 static int proc_get_stats_ap(char *page, char **start, off_t offset, int count,
487                                                         int *eof, void *data)
488 {
489         struct net_device *dev = data;
490         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
491         struct ieee80211_device *ieee = priv->ieee80211;
492         struct ieee80211_network *target;
493
494         int len = 0;
495
496         list_for_each_entry(target, &ieee->network_list, list) {
497
498                 len += snprintf(page + len, count - len, "%s ", target->ssid);
499
500                 if (target->wpa_ie_len > 0 || target->rsn_ie_len > 0)
501                         len += snprintf(page + len, count - len, "WPA\n");
502                 else
503                         len += snprintf(page + len, count - len, "non_WPA\n");
504         }
505
506         *eof = 1;
507         return len;
508 }
509
510 static int proc_get_registers(char *page, char **start,
511                           off_t offset, int count,
512                           int *eof, void *data)
513 {
514         struct net_device *dev = data;
515 //      struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
516
517         int len = 0;
518         int i,n;
519
520         int max=0xff;
521
522         /* This dump the current register page */
523 len += snprintf(page + len, count - len,
524                         "\n####################page 0##################\n ");
525
526         for(n=0;n<=max;)
527         {
528                 //printk( "\nD: %2x> ", n);
529                 len += snprintf(page + len, count - len,
530                         "\nD:  %2x > ",n);
531
532                 for(i=0;i<16 && n<=max;i++,n++)
533                 len += snprintf(page + len, count - len,
534                         "%2x ",read_nic_byte(dev,0x000|n));
535
536                 //      printk("%2x ",read_nic_byte(dev,n));
537         }
538 len += snprintf(page + len, count - len,
539                         "\n####################page 1##################\n ");
540         for(n=0;n<=max;)
541         {
542                 //printk( "\nD: %2x> ", n);
543                 len += snprintf(page + len, count - len,
544                         "\nD:  %2x > ",n);
545
546                 for(i=0;i<16 && n<=max;i++,n++)
547                 len += snprintf(page + len, count - len,
548                         "%2x ",read_nic_byte(dev,0x100|n));
549
550                 //      printk("%2x ",read_nic_byte(dev,n));
551         }
552 len += snprintf(page + len, count - len,
553                         "\n####################page 3##################\n ");
554         for(n=0;n<=max;)
555         {
556                 //printk( "\nD: %2x> ", n);
557                 len += snprintf(page + len, count - len,
558                         "\nD:  %2x > ",n);
559
560                 for(i=0;i<16 && n<=max;i++,n++)
561                 len += snprintf(page + len, count - len,
562                         "%2x ",read_nic_byte(dev,0x300|n));
563
564                 //      printk("%2x ",read_nic_byte(dev,n));
565         }
566
567
568         len += snprintf(page + len, count - len,"\n");
569         *eof = 1;
570         return len;
571
572 }
573
574
575
576
577
578 static int proc_get_stats_tx(char *page, char **start,
579                           off_t offset, int count,
580                           int *eof, void *data)
581 {
582         struct net_device *dev = data;
583         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
584
585         int len = 0;
586
587         len += snprintf(page + len, count - len,
588                 "TX VI priority ok int: %lu\n"
589                 "TX VI priority error int: %lu\n"
590                 "TX VO priority ok int: %lu\n"
591                 "TX VO priority error int: %lu\n"
592                 "TX BE priority ok int: %lu\n"
593                 "TX BE priority error int: %lu\n"
594                 "TX BK priority ok int: %lu\n"
595                 "TX BK priority error int: %lu\n"
596                 "TX MANAGE priority ok int: %lu\n"
597                 "TX MANAGE priority error int: %lu\n"
598                 "TX BEACON priority ok int: %lu\n"
599                 "TX BEACON priority error int: %lu\n"
600 //              "TX high priority ok int: %lu\n"
601 //              "TX high priority failed error int: %lu\n"
602                 "TX queue resume: %lu\n"
603                 "TX queue stopped?: %d\n"
604                 "TX fifo overflow: %lu\n"
605 //              "TX beacon: %lu\n"
606                 "TX VI queue: %d\n"
607                 "TX VO queue: %d\n"
608                 "TX BE queue: %d\n"
609                 "TX BK queue: %d\n"
610 //              "TX HW queue: %d\n"
611                 "TX VI dropped: %lu\n"
612                 "TX VO dropped: %lu\n"
613                 "TX BE dropped: %lu\n"
614                 "TX BK dropped: %lu\n"
615                 "TX total data packets %lu\n",
616 //              "TX beacon aborted: %lu\n",
617                 priv->stats.txviokint,
618                 priv->stats.txvierr,
619                 priv->stats.txvookint,
620                 priv->stats.txvoerr,
621                 priv->stats.txbeokint,
622                 priv->stats.txbeerr,
623                 priv->stats.txbkokint,
624                 priv->stats.txbkerr,
625                 priv->stats.txmanageokint,
626                 priv->stats.txmanageerr,
627                 priv->stats.txbeaconokint,
628                 priv->stats.txbeaconerr,
629 //              priv->stats.txhpokint,
630 //              priv->stats.txhperr,
631                 priv->stats.txresumed,
632                 netif_queue_stopped(dev),
633                 priv->stats.txoverflow,
634 //              priv->stats.txbeacon,
635                 atomic_read(&(priv->tx_pending[VI_PRIORITY])),
636                 atomic_read(&(priv->tx_pending[VO_PRIORITY])),
637                 atomic_read(&(priv->tx_pending[BE_PRIORITY])),
638                 atomic_read(&(priv->tx_pending[BK_PRIORITY])),
639 //              read_nic_byte(dev, TXFIFOCOUNT),
640                 priv->stats.txvidrop,
641                 priv->stats.txvodrop,
642                 priv->stats.txbedrop,
643                 priv->stats.txbkdrop,
644                 priv->stats.txdatapkt
645 //              priv->stats.txbeaconerr
646                 );
647
648         *eof = 1;
649         return len;
650 }
651
652
653
654 static int proc_get_stats_rx(char *page, char **start,
655                           off_t offset, int count,
656                           int *eof, void *data)
657 {
658         struct net_device *dev = data;
659         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
660
661         int len = 0;
662
663         len += snprintf(page + len, count - len,
664                 "RX packets: %lu\n"
665                 "RX urb status error: %lu\n"
666                 "RX invalid urb error: %lu\n",
667                 priv->stats.rxoktotal,
668                 priv->stats.rxstaterr,
669                 priv->stats.rxurberr);
670
671         *eof = 1;
672         return len;
673 }
674 void rtl8192_proc_module_init(void)
675 {
676         RT_TRACE(COMP_INIT, "Initializing proc filesystem");
677         rtl8192_proc=create_proc_entry(RTL819xU_MODULE_NAME, S_IFDIR, init_net.proc_net);
678 }
679
680
681 void rtl8192_proc_module_remove(void)
682 {
683         remove_proc_entry(RTL819xU_MODULE_NAME, init_net.proc_net);
684 }
685
686
687 void rtl8192_proc_remove_one(struct net_device *dev)
688 {
689         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
690
691
692         if (priv->dir_dev) {
693         //      remove_proc_entry("stats-hw", priv->dir_dev);
694                 remove_proc_entry("stats-tx", priv->dir_dev);
695                 remove_proc_entry("stats-rx", priv->dir_dev);
696         //      remove_proc_entry("stats-ieee", priv->dir_dev);
697                 remove_proc_entry("stats-ap", priv->dir_dev);
698                 remove_proc_entry("registers", priv->dir_dev);
699         //      remove_proc_entry("cck-registers",priv->dir_dev);
700         //      remove_proc_entry("ofdm-registers",priv->dir_dev);
701                 //remove_proc_entry(dev->name, rtl8192_proc);
702                 remove_proc_entry("wlan0", rtl8192_proc);
703                 priv->dir_dev = NULL;
704         }
705 }
706
707
708 void rtl8192_proc_init_one(struct net_device *dev)
709 {
710         struct proc_dir_entry *e;
711         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
712         priv->dir_dev = create_proc_entry(dev->name,
713                                           S_IFDIR | S_IRUGO | S_IXUGO,
714                                           rtl8192_proc);
715         if (!priv->dir_dev) {
716                 RT_TRACE(COMP_ERR, "Unable to initialize /proc/net/rtl8192/%s\n",
717                       dev->name);
718                 return;
719         }
720         e = create_proc_read_entry("stats-rx", S_IFREG | S_IRUGO,
721                                    priv->dir_dev, proc_get_stats_rx, dev);
722
723         if (!e) {
724                 RT_TRACE(COMP_ERR,"Unable to initialize "
725                       "/proc/net/rtl8192/%s/stats-rx\n",
726                       dev->name);
727         }
728
729
730         e = create_proc_read_entry("stats-tx", S_IFREG | S_IRUGO,
731                                    priv->dir_dev, proc_get_stats_tx, dev);
732
733         if (!e) {
734                 RT_TRACE(COMP_ERR, "Unable to initialize "
735                       "/proc/net/rtl8192/%s/stats-tx\n",
736                       dev->name);
737         }
738
739         e = create_proc_read_entry("stats-ap", S_IFREG | S_IRUGO,
740                                    priv->dir_dev, proc_get_stats_ap, dev);
741
742         if (!e) {
743                 RT_TRACE(COMP_ERR, "Unable to initialize "
744                       "/proc/net/rtl8192/%s/stats-ap\n",
745                       dev->name);
746         }
747
748         e = create_proc_read_entry("registers", S_IFREG | S_IRUGO,
749                                    priv->dir_dev, proc_get_registers, dev);
750         if (!e) {
751                 RT_TRACE(COMP_ERR, "Unable to initialize "
752                       "/proc/net/rtl8192/%s/registers\n",
753                       dev->name);
754         }
755 }
756 /****************************************************************************
757    -----------------------------MISC STUFF-------------------------
758 *****************************************************************************/
759
760 /* this is only for debugging */
761 void print_buffer(u32 *buffer, int len)
762 {
763         int i;
764         u8 *buf =(u8*)buffer;
765
766         printk("ASCII BUFFER DUMP (len: %x):\n",len);
767
768         for(i=0;i<len;i++)
769                 printk("%c",buf[i]);
770
771         printk("\nBINARY BUFFER DUMP (len: %x):\n",len);
772
773         for(i=0;i<len;i++)
774                 printk("%x",buf[i]);
775
776         printk("\n");
777 }
778
779 //short check_nic_enough_desc(struct net_device *dev, priority_t priority)
780 short check_nic_enough_desc(struct net_device *dev,int queue_index)
781 {
782         struct r8192_priv *priv = ieee80211_priv(dev);
783         int used = atomic_read(&priv->tx_pending[queue_index]);
784
785         return (used < MAX_TX_URB);
786 }
787
788 void tx_timeout(struct net_device *dev)
789 {
790         struct r8192_priv *priv = ieee80211_priv(dev);
791         //rtl8192_commit(dev);
792
793         schedule_work(&priv->reset_wq);
794         //DMESG("TXTIMEOUT");
795 }
796
797
798 /* this is only for debug */
799 void dump_eprom(struct net_device *dev)
800 {
801         int i;
802         for(i=0; i<63; i++)
803                 RT_TRACE(COMP_EPROM, "EEPROM addr %x : %x", i, eprom_read(dev,i));
804 }
805
806 /* this is only for debug */
807 void rtl8192_dump_reg(struct net_device *dev)
808 {
809         int i;
810         int n;
811         int max=0x1ff;
812
813         RT_TRACE(COMP_PHY, "Dumping NIC register map");
814
815         for(n=0;n<=max;)
816         {
817                 printk( "\nD: %2x> ", n);
818                 for(i=0;i<16 && n<=max;i++,n++)
819                         printk("%2x ",read_nic_byte(dev,n));
820         }
821         printk("\n");
822 }
823
824 /****************************************************************************
825       ------------------------------HW STUFF---------------------------
826 *****************************************************************************/
827
828
829 void rtl8192_set_mode(struct net_device *dev,int mode)
830 {
831         u8 ecmd;
832         ecmd=read_nic_byte(dev, EPROM_CMD);
833         ecmd=ecmd &~ EPROM_CMD_OPERATING_MODE_MASK;
834         ecmd=ecmd | (mode<<EPROM_CMD_OPERATING_MODE_SHIFT);
835         ecmd=ecmd &~ (1<<EPROM_CS_SHIFT);
836         ecmd=ecmd &~ (1<<EPROM_CK_SHIFT);
837         write_nic_byte(dev, EPROM_CMD, ecmd);
838 }
839
840
841 void rtl8192_update_msr(struct net_device *dev)
842 {
843         struct r8192_priv *priv = ieee80211_priv(dev);
844         u8 msr;
845
846         msr  = read_nic_byte(dev, MSR);
847         msr &= ~ MSR_LINK_MASK;
848
849         /* do not change in link_state != WLAN_LINK_ASSOCIATED.
850          * msr must be updated if the state is ASSOCIATING.
851          * this is intentional and make sense for ad-hoc and
852          * master (see the create BSS/IBSS func)
853          */
854         if (priv->ieee80211->state == IEEE80211_LINKED){
855
856                 if (priv->ieee80211->iw_mode == IW_MODE_INFRA)
857                         msr |= (MSR_LINK_MANAGED<<MSR_LINK_SHIFT);
858                 else if (priv->ieee80211->iw_mode == IW_MODE_ADHOC)
859                         msr |= (MSR_LINK_ADHOC<<MSR_LINK_SHIFT);
860                 else if (priv->ieee80211->iw_mode == IW_MODE_MASTER)
861                         msr |= (MSR_LINK_MASTER<<MSR_LINK_SHIFT);
862
863         }else
864                 msr |= (MSR_LINK_NONE<<MSR_LINK_SHIFT);
865
866         write_nic_byte(dev, MSR, msr);
867 }
868
869 void rtl8192_set_chan(struct net_device *dev,short ch)
870 {
871         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
872 //      u32 tx;
873         RT_TRACE(COMP_CH, "=====>%s()====ch:%d\n", __FUNCTION__, ch);
874         priv->chan=ch;
875
876         /* this hack should avoid frame TX during channel setting*/
877
878
879 //      tx = read_nic_dword(dev,TX_CONF);
880 //      tx &= ~TX_LOOPBACK_MASK;
881
882 #ifndef LOOP_TEST
883 //      write_nic_dword(dev,TX_CONF, tx |( TX_LOOPBACK_MAC<<TX_LOOPBACK_SHIFT));
884
885         //need to implement rf set channel here WB
886
887         if (priv->rf_set_chan)
888         priv->rf_set_chan(dev,priv->chan);
889         mdelay(10);
890 //      write_nic_dword(dev,TX_CONF,tx | (TX_LOOPBACK_NONE<<TX_LOOPBACK_SHIFT));
891 #endif
892 }
893
894 static void rtl8192_rx_isr(struct urb *urb);
895 //static void rtl8192_rx_isr(struct urb *rx_urb);
896
897 u32 get_rxpacket_shiftbytes_819xusb(struct ieee80211_rx_stats *pstats)
898 {
899
900 #ifdef USB_RX_AGGREGATION_SUPPORT
901         if (pstats->bisrxaggrsubframe)
902                 return (sizeof(rx_desc_819x_usb) + pstats->RxDrvInfoSize
903                         + pstats->RxBufShift + 8);
904         else
905 #endif
906                 return (sizeof(rx_desc_819x_usb) + pstats->RxDrvInfoSize
907                                 + pstats->RxBufShift);
908
909 }
910 static int rtl8192_rx_initiate(struct net_device*dev)
911 {
912         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
913         struct urb *entry;
914         struct sk_buff *skb;
915         struct rtl8192_rx_info *info;
916
917         /* nomal packet rx procedure */
918         while (skb_queue_len(&priv->rx_queue) < MAX_RX_URB) {
919                 skb = __dev_alloc_skb(RX_URB_SIZE, GFP_KERNEL);
920                 if (!skb)
921                         break;
922                 entry = usb_alloc_urb(0, GFP_KERNEL);
923                 if (!entry) {
924                         kfree_skb(skb);
925                         break;
926                 }
927 //              printk("nomal packet IN request!\n");
928                 usb_fill_bulk_urb(entry, priv->udev,
929                                   usb_rcvbulkpipe(priv->udev, 3), skb_tail_pointer(skb),
930                                   RX_URB_SIZE, rtl8192_rx_isr, skb);
931                 info = (struct rtl8192_rx_info *) skb->cb;
932                 info->urb = entry;
933                 info->dev = dev;
934                 info->out_pipe = 3; //denote rx normal packet queue
935                 skb_queue_tail(&priv->rx_queue, skb);
936                 usb_submit_urb(entry, GFP_KERNEL);
937         }
938
939         /* command packet rx procedure */
940         while (skb_queue_len(&priv->rx_queue) < MAX_RX_URB + 3) {
941 //              printk("command packet IN request!\n");
942                 skb = __dev_alloc_skb(RX_URB_SIZE ,GFP_KERNEL);
943                 if (!skb)
944                         break;
945                 entry = usb_alloc_urb(0, GFP_KERNEL);
946                 if (!entry) {
947                         kfree_skb(skb);
948                         break;
949                 }
950                 usb_fill_bulk_urb(entry, priv->udev,
951                                   usb_rcvbulkpipe(priv->udev, 9), skb_tail_pointer(skb),
952                                   RX_URB_SIZE, rtl8192_rx_isr, skb);
953                 info = (struct rtl8192_rx_info *) skb->cb;
954                 info->urb = entry;
955                 info->dev = dev;
956                    info->out_pipe = 9; //denote rx cmd packet queue
957                 skb_queue_tail(&priv->rx_queue, skb);
958                 usb_submit_urb(entry, GFP_KERNEL);
959         }
960
961         return 0;
962 }
963
964 void rtl8192_set_rxconf(struct net_device *dev)
965 {
966         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
967         u32 rxconf;
968
969         rxconf=read_nic_dword(dev,RCR);
970         rxconf = rxconf &~ MAC_FILTER_MASK;
971         rxconf = rxconf | RCR_AMF;
972         rxconf = rxconf | RCR_ADF;
973         rxconf = rxconf | RCR_AB;
974         rxconf = rxconf | RCR_AM;
975         //rxconf = rxconf | RCR_ACF;
976
977         if (dev->flags & IFF_PROMISC) {DMESG ("NIC in promisc mode");}
978
979         if(priv->ieee80211->iw_mode == IW_MODE_MONITOR || \
980            dev->flags & IFF_PROMISC){
981                 rxconf = rxconf | RCR_AAP;
982         } /*else if(priv->ieee80211->iw_mode == IW_MODE_MASTER){
983                 rxconf = rxconf | (1<<ACCEPT_ALLMAC_FRAME_SHIFT);
984                 rxconf = rxconf | (1<<RX_CHECK_BSSID_SHIFT);
985         }*/else{
986                 rxconf = rxconf | RCR_APM;
987                 rxconf = rxconf | RCR_CBSSID;
988         }
989
990
991         if(priv->ieee80211->iw_mode == IW_MODE_MONITOR){
992                 rxconf = rxconf | RCR_AICV;
993                 rxconf = rxconf | RCR_APWRMGT;
994         }
995
996         if( priv->crcmon == 1 && priv->ieee80211->iw_mode == IW_MODE_MONITOR)
997                 rxconf = rxconf | RCR_ACRC32;
998
999
1000         rxconf = rxconf &~ RX_FIFO_THRESHOLD_MASK;
1001         rxconf = rxconf | (RX_FIFO_THRESHOLD_NONE<<RX_FIFO_THRESHOLD_SHIFT);
1002         rxconf = rxconf &~ MAX_RX_DMA_MASK;
1003         rxconf = rxconf | ((u32)7<<RCR_MXDMA_OFFSET);
1004
1005 //      rxconf = rxconf | (1<<RX_AUTORESETPHY_SHIFT);
1006         rxconf = rxconf | RCR_ONLYERLPKT;
1007
1008 //      rxconf = rxconf &~ RCR_CS_MASK;
1009 //      rxconf = rxconf | (1<<RCR_CS_SHIFT);
1010
1011         write_nic_dword(dev, RCR, rxconf);
1012
1013         #ifdef DEBUG_RX
1014         DMESG("rxconf: %x %x",rxconf ,read_nic_dword(dev,RCR));
1015         #endif
1016 }
1017 //wait to be removed
1018 void rtl8192_rx_enable(struct net_device *dev)
1019 {
1020         //u8 cmd;
1021
1022         //struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
1023
1024         rtl8192_rx_initiate(dev);
1025
1026 //      rtl8192_set_rxconf(dev);
1027 }
1028
1029
1030 void rtl8192_tx_enable(struct net_device *dev)
1031 {
1032 }
1033
1034
1035
1036 void rtl8192_rtx_disable(struct net_device *dev)
1037 {
1038         u8 cmd;
1039         struct r8192_priv *priv = ieee80211_priv(dev);
1040         struct sk_buff *skb;
1041         struct rtl8192_rx_info *info;
1042
1043         cmd=read_nic_byte(dev,CMDR);
1044         write_nic_byte(dev, CMDR, cmd &~ \
1045                 (CR_TE|CR_RE));
1046         force_pci_posting(dev);
1047         mdelay(10);
1048
1049         while ((skb = __skb_dequeue(&priv->rx_queue))) {
1050                 info = (struct rtl8192_rx_info *) skb->cb;
1051                 if (!info->urb)
1052                         continue;
1053
1054                 usb_kill_urb(info->urb);
1055                 kfree_skb(skb);
1056         }
1057
1058         if (skb_queue_len(&priv->skb_queue)) {
1059                 printk(KERN_WARNING "skb_queue not empty\n");
1060         }
1061
1062         skb_queue_purge(&priv->skb_queue);
1063         return;
1064 }
1065
1066
1067 int alloc_tx_beacon_desc_ring(struct net_device *dev, int count)
1068 {
1069         return 0;
1070 }
1071
1072 inline u16 ieeerate2rtlrate(int rate)
1073 {
1074         switch(rate){
1075         case 10:
1076         return 0;
1077         case 20:
1078         return 1;
1079         case 55:
1080         return 2;
1081         case 110:
1082         return 3;
1083         case 60:
1084         return 4;
1085         case 90:
1086         return 5;
1087         case 120:
1088         return 6;
1089         case 180:
1090         return 7;
1091         case 240:
1092         return 8;
1093         case 360:
1094         return 9;
1095         case 480:
1096         return 10;
1097         case 540:
1098         return 11;
1099         default:
1100         return 3;
1101
1102         }
1103 }
1104 static u16 rtl_rate[] = {10,20,55,110,60,90,120,180,240,360,480,540};
1105 inline u16 rtl8192_rate2rate(short rate)
1106 {
1107         if (rate >11) return 0;
1108         return rtl_rate[rate];
1109 }
1110
1111
1112 /* The protype of rx_isr has changed since one verion of Linux Kernel */
1113 static void rtl8192_rx_isr(struct urb *urb)
1114 {
1115         struct sk_buff *skb = (struct sk_buff *) urb->context;
1116         struct rtl8192_rx_info *info = (struct rtl8192_rx_info *)skb->cb;
1117         struct net_device *dev = info->dev;
1118         struct r8192_priv *priv = ieee80211_priv(dev);
1119         int out_pipe = info->out_pipe;
1120         int err;
1121         if(!priv->up)
1122                 return;
1123         if (unlikely(urb->status)) {
1124                 info->urb = NULL;
1125                 priv->stats.rxstaterr++;
1126                 priv->ieee80211->stats.rx_errors++;
1127                 usb_free_urb(urb);
1128         //      printk("%s():rx status err\n",__FUNCTION__);
1129                 return;
1130         }
1131         skb_unlink(skb, &priv->rx_queue);
1132         skb_put(skb, urb->actual_length);
1133
1134         skb_queue_tail(&priv->skb_queue, skb);
1135         tasklet_schedule(&priv->irq_rx_tasklet);
1136
1137         skb = dev_alloc_skb(RX_URB_SIZE);
1138         if (unlikely(!skb)) {
1139                 usb_free_urb(urb);
1140                 printk("%s():can,t alloc skb\n",__FUNCTION__);
1141                 /* TODO check rx queue length and refill *somewhere* */
1142                 return;
1143         }
1144
1145         usb_fill_bulk_urb(urb, priv->udev,
1146                         usb_rcvbulkpipe(priv->udev, out_pipe), skb_tail_pointer(skb),
1147                         RX_URB_SIZE, rtl8192_rx_isr, skb);
1148
1149         info = (struct rtl8192_rx_info *) skb->cb;
1150         info->urb = urb;
1151         info->dev = dev;
1152         info->out_pipe = out_pipe;
1153
1154         urb->transfer_buffer = skb_tail_pointer(skb);
1155         urb->context = skb;
1156         skb_queue_tail(&priv->rx_queue, skb);
1157         err = usb_submit_urb(urb, GFP_ATOMIC);
1158         if(err && err != EPERM)
1159                 printk("can not submit rxurb, err is %x,URB status is %x\n",err,urb->status);
1160 }
1161
1162 u32
1163 rtl819xusb_rx_command_packet(
1164         struct net_device *dev,
1165         struct ieee80211_rx_stats *pstats
1166         )
1167 {
1168         u32     status;
1169
1170         //RT_TRACE(COMP_RECV, DBG_TRACE, ("---> RxCommandPacketHandle819xUsb()\n"));
1171
1172         status = cmpk_message_handle_rx(dev, pstats);
1173         if (status)
1174         {
1175                 DMESG("rxcommandpackethandle819xusb: It is a command packet\n");
1176         }
1177         else
1178         {
1179                 //RT_TRACE(COMP_RECV, DBG_TRACE, ("RxCommandPacketHandle819xUsb: It is not a command packet\n"));
1180         }
1181
1182         //RT_TRACE(COMP_RECV, DBG_TRACE, ("<--- RxCommandPacketHandle819xUsb()\n"));
1183         return status;
1184 }
1185
1186
1187 void rtl8192_data_hard_stop(struct net_device *dev)
1188 {
1189         //FIXME !!
1190 }
1191
1192
1193 void rtl8192_data_hard_resume(struct net_device *dev)
1194 {
1195         // FIXME !!
1196 }
1197
1198 /* this function TX data frames when the ieee80211 stack requires this.
1199  * It checks also if we need to stop the ieee tx queue, eventually do it
1200  */
1201 void rtl8192_hard_data_xmit(struct sk_buff *skb, struct net_device *dev, int rate)
1202 {
1203         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
1204         int ret;
1205         unsigned long flags;
1206         cb_desc *tcb_desc = (cb_desc *)(skb->cb + MAX_DEV_ADDR_SIZE);
1207         u8 queue_index = tcb_desc->queue_index;
1208
1209         /* shall not be referred by command packet */
1210         assert(queue_index != TXCMD_QUEUE);
1211
1212         spin_lock_irqsave(&priv->tx_lock,flags);
1213
1214         memcpy((unsigned char *)(skb->cb),&dev,sizeof(dev));
1215 //      tcb_desc->RATRIndex = 7;
1216 //      tcb_desc->bTxDisableRateFallBack = 1;
1217 //      tcb_desc->bTxUseDriverAssingedRate = 1;
1218         tcb_desc->bTxEnableFwCalcDur = 1;
1219         skb_push(skb, priv->ieee80211->tx_headroom);
1220         ret = rtl8192_tx(dev, skb);
1221
1222         //priv->ieee80211->stats.tx_bytes+=(skb->len - priv->ieee80211->tx_headroom);
1223         //priv->ieee80211->stats.tx_packets++;
1224
1225         spin_unlock_irqrestore(&priv->tx_lock,flags);
1226
1227 //      return ret;
1228         return;
1229 }
1230
1231 /* This is a rough attempt to TX a frame
1232  * This is called by the ieee 80211 stack to TX management frames.
1233  * If the ring is full packet are dropped (for data frame the queue
1234  * is stopped before this can happen).
1235  */
1236 int rtl8192_hard_start_xmit(struct sk_buff *skb,struct net_device *dev)
1237 {
1238         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
1239         int ret;
1240         unsigned long flags;
1241         cb_desc *tcb_desc = (cb_desc *)(skb->cb + MAX_DEV_ADDR_SIZE);
1242         u8 queue_index = tcb_desc->queue_index;
1243
1244
1245         spin_lock_irqsave(&priv->tx_lock,flags);
1246
1247         memcpy((unsigned char *)(skb->cb),&dev,sizeof(dev));
1248         if(queue_index == TXCMD_QUEUE) {
1249                 skb_push(skb, USB_HWDESC_HEADER_LEN);
1250                 rtl819xU_tx_cmd(dev, skb);
1251                 ret = 1;
1252                 spin_unlock_irqrestore(&priv->tx_lock,flags);
1253                 return ret;
1254         } else {
1255                 skb_push(skb, priv->ieee80211->tx_headroom);
1256                 ret = rtl8192_tx(dev, skb);
1257         }
1258
1259         spin_unlock_irqrestore(&priv->tx_lock,flags);
1260
1261         return ret;
1262 }
1263
1264
1265 void rtl8192_try_wake_queue(struct net_device *dev, int pri);
1266
1267 #ifdef USB_TX_DRIVER_AGGREGATION_ENABLE
1268 u16 DrvAggr_PaddingAdd(struct net_device *dev, struct sk_buff *skb)
1269 {
1270         u16     PaddingNum =  256 - ((skb->len + TX_PACKET_DRVAGGR_SUBFRAME_SHIFT_BYTES) % 256);
1271         return  (PaddingNum&0xff);
1272 }
1273
1274 u8 MRateToHwRate8190Pci(u8 rate);
1275 u8 QueryIsShort(u8 TxHT, u8 TxRate, cb_desc *tcb_desc);
1276 u8 MapHwQueueToFirmwareQueue(u8 QueueID);
1277 struct sk_buff *DrvAggr_Aggregation(struct net_device *dev, struct ieee80211_drv_agg_txb *pSendList)
1278 {
1279         struct ieee80211_device *ieee = netdev_priv(dev);
1280         struct r8192_priv *priv = ieee80211_priv(dev);
1281         cb_desc         *tcb_desc = NULL;
1282         u8              i;
1283         u32             TotalLength;
1284         struct sk_buff  *skb;
1285         struct sk_buff  *agg_skb;
1286         tx_desc_819x_usb_aggr_subframe *tx_agg_desc = NULL;
1287         tx_fwinfo_819x_usb             *tx_fwinfo = NULL;
1288
1289         //
1290         // Local variable initialization.
1291         //
1292         /* first skb initialization */
1293         skb = pSendList->tx_agg_frames[0];
1294         TotalLength = skb->len;
1295
1296         /* Get the total aggregation length including the padding space and
1297          * sub frame header.
1298          */
1299         for(i = 1; i < pSendList->nr_drv_agg_frames; i++) {
1300                 TotalLength += DrvAggr_PaddingAdd(dev, skb);
1301                 skb = pSendList->tx_agg_frames[i];
1302                 TotalLength += (skb->len + TX_PACKET_DRVAGGR_SUBFRAME_SHIFT_BYTES);
1303         }
1304
1305         /* allocate skb to contain the aggregated packets */
1306         agg_skb = dev_alloc_skb(TotalLength + ieee->tx_headroom);
1307         memset(agg_skb->data, 0, agg_skb->len);
1308         skb_reserve(agg_skb, ieee->tx_headroom);
1309
1310 //      RT_DEBUG_DATA(COMP_SEND, skb->cb, sizeof(skb->cb));
1311         /* reserve info for first subframe Tx descriptor to be set in the tx function */
1312         skb = pSendList->tx_agg_frames[0];
1313         tcb_desc = (cb_desc *)(skb->cb + MAX_DEV_ADDR_SIZE);
1314         tcb_desc->drv_agg_enable = 1;
1315         tcb_desc->pkt_size = skb->len;
1316         tcb_desc->DrvAggrNum = pSendList->nr_drv_agg_frames;
1317         printk("DrvAggNum = %d\n", tcb_desc->DrvAggrNum);
1318 //      RT_DEBUG_DATA(COMP_SEND, skb->cb, sizeof(skb->cb));
1319 //      printk("========>skb->data ======> \n");
1320 //      RT_DEBUG_DATA(COMP_SEND, skb->data, skb->len);
1321         memcpy(agg_skb->cb, skb->cb, sizeof(skb->cb));
1322         memcpy(skb_put(agg_skb,skb->len),skb->data,skb->len);
1323
1324         for(i = 1; i < pSendList->nr_drv_agg_frames; i++) {
1325                 /* push the next sub frame to be 256 byte aline */
1326                 skb_put(agg_skb,DrvAggr_PaddingAdd(dev,skb));
1327
1328                 /* Subframe drv Tx descriptor and firmware info setting */
1329                 skb = pSendList->tx_agg_frames[i];
1330                 tcb_desc = (cb_desc *)(skb->cb + MAX_DEV_ADDR_SIZE);
1331                 tx_agg_desc = (tx_desc_819x_usb_aggr_subframe *)agg_skb->tail;
1332                 tx_fwinfo = (tx_fwinfo_819x_usb *)(agg_skb->tail + sizeof(tx_desc_819x_usb_aggr_subframe));
1333
1334                 memset(tx_fwinfo,0,sizeof(tx_fwinfo_819x_usb));
1335                 /* DWORD 0 */
1336                 tx_fwinfo->TxHT = (tcb_desc->data_rate&0x80)?1:0;
1337                 tx_fwinfo->TxRate = MRateToHwRate8190Pci(tcb_desc->data_rate);
1338                 tx_fwinfo->EnableCPUDur = tcb_desc->bTxEnableFwCalcDur;
1339                 tx_fwinfo->Short = QueryIsShort(tx_fwinfo->TxHT, tx_fwinfo->TxRate, tcb_desc);
1340                 if(tcb_desc->bAMPDUEnable) {//AMPDU enabled
1341                         tx_fwinfo->AllowAggregation = 1;
1342                         /* DWORD 1 */
1343                         tx_fwinfo->RxMF = tcb_desc->ampdu_factor;
1344                         tx_fwinfo->RxAMD = tcb_desc->ampdu_density&0x07;//ampdudensity
1345                 } else {
1346                         tx_fwinfo->AllowAggregation = 0;
1347                         /* DWORD 1 */
1348                         tx_fwinfo->RxMF = 0;
1349                         tx_fwinfo->RxAMD = 0;
1350                 }
1351
1352                 /* Protection mode related */
1353                 tx_fwinfo->RtsEnable = (tcb_desc->bRTSEnable)?1:0;
1354                 tx_fwinfo->CtsEnable = (tcb_desc->bCTSEnable)?1:0;
1355                 tx_fwinfo->RtsSTBC = (tcb_desc->bRTSSTBC)?1:0;
1356                 tx_fwinfo->RtsHT = (tcb_desc->rts_rate&0x80)?1:0;
1357                 tx_fwinfo->RtsRate =  MRateToHwRate8190Pci((u8)tcb_desc->rts_rate);
1358                 tx_fwinfo->RtsSubcarrier = (tx_fwinfo->RtsHT==0)?(tcb_desc->RTSSC):0;
1359                 tx_fwinfo->RtsBandwidth = (tx_fwinfo->RtsHT==1)?((tcb_desc->bRTSBW)?1:0):0;
1360                 tx_fwinfo->RtsShort = (tx_fwinfo->RtsHT==0)?(tcb_desc->bRTSUseShortPreamble?1:0):\
1361                                       (tcb_desc->bRTSUseShortGI?1:0);
1362
1363                 /* Set Bandwidth and sub-channel settings. */
1364                 if(priv->CurrentChannelBW == HT_CHANNEL_WIDTH_20_40)
1365                 {
1366                         if(tcb_desc->bPacketBW) {
1367                                 tx_fwinfo->TxBandwidth = 1;
1368                                 tx_fwinfo->TxSubCarrier = 0;    //By SD3's Jerry suggestion, use duplicated mode
1369                         } else {
1370                                 tx_fwinfo->TxBandwidth = 0;
1371                                 tx_fwinfo->TxSubCarrier = priv->nCur40MhzPrimeSC;
1372                         }
1373                 } else {
1374                         tx_fwinfo->TxBandwidth = 0;
1375                         tx_fwinfo->TxSubCarrier = 0;
1376                 }
1377
1378                 /* Fill Tx descriptor */
1379                 memset(tx_agg_desc, 0, sizeof(tx_desc_819x_usb_aggr_subframe));
1380                 /* DWORD 0 */
1381                 //tx_agg_desc->LINIP = 0;
1382                 //tx_agg_desc->CmdInit = 1;
1383                 tx_agg_desc->Offset =  sizeof(tx_fwinfo_819x_usb) + 8;
1384                 /* already raw data, need not to substract header length */
1385                 tx_agg_desc->PktSize = skb->len & 0xffff;
1386
1387                 /*DWORD 1*/
1388                 tx_agg_desc->SecCAMID= 0;
1389                 tx_agg_desc->RATid = tcb_desc->RATRIndex;
1390                 {
1391                         //MPDUOverhead = 0;
1392                         tx_agg_desc->NoEnc = 1;
1393                 }
1394                 tx_agg_desc->SecType = 0x0;
1395
1396                 if (tcb_desc->bHwSec) {
1397                         switch (priv->ieee80211->pairwise_key_type)
1398                         {
1399                                 case KEY_TYPE_WEP40:
1400                                 case KEY_TYPE_WEP104:
1401                                         tx_agg_desc->SecType = 0x1;
1402                                         tx_agg_desc->NoEnc = 0;
1403                                         break;
1404                                 case KEY_TYPE_TKIP:
1405                                         tx_agg_desc->SecType = 0x2;
1406                                         tx_agg_desc->NoEnc = 0;
1407                                         break;
1408                                 case KEY_TYPE_CCMP:
1409                                         tx_agg_desc->SecType = 0x3;
1410                                         tx_agg_desc->NoEnc = 0;
1411                                         break;
1412                                 case KEY_TYPE_NA:
1413                                         tx_agg_desc->SecType = 0x0;
1414                                         tx_agg_desc->NoEnc = 1;
1415                                         break;
1416                         }
1417                 }
1418
1419                 tx_agg_desc->QueueSelect = MapHwQueueToFirmwareQueue(tcb_desc->queue_index);
1420                 tx_agg_desc->TxFWInfoSize =  sizeof(tx_fwinfo_819x_usb);
1421
1422                 tx_agg_desc->DISFB = tcb_desc->bTxDisableRateFallBack;
1423                 tx_agg_desc->USERATE = tcb_desc->bTxUseDriverAssingedRate;
1424
1425                 tx_agg_desc->OWN = 1;
1426
1427                 //DWORD 2
1428                 /* According windows driver, it seems that there no need to fill this field */
1429                 //tx_agg_desc->TxBufferSize= (u32)(skb->len - USB_HWDESC_HEADER_LEN);
1430
1431                 /* to fill next packet */
1432                 skb_put(agg_skb,TX_PACKET_DRVAGGR_SUBFRAME_SHIFT_BYTES);
1433                 memcpy(skb_put(agg_skb,skb->len),skb->data,skb->len);
1434         }
1435
1436         for(i = 0; i < pSendList->nr_drv_agg_frames; i++) {
1437                 dev_kfree_skb_any(pSendList->tx_agg_frames[i]);
1438         }
1439
1440         return agg_skb;
1441 }
1442
1443 /* NOTE:
1444         This function return a list of PTCB which is proper to be aggregate with the input TCB.
1445         If no proper TCB is found to do aggregation, SendList will only contain the input TCB.
1446 */
1447 u8 DrvAggr_GetAggregatibleList(struct net_device *dev, struct sk_buff *skb,
1448                 struct ieee80211_drv_agg_txb *pSendList)
1449 {
1450         struct ieee80211_device *ieee = netdev_priv(dev);
1451         PRT_HIGH_THROUGHPUT     pHTInfo = ieee->pHTInfo;
1452         u16             nMaxAggrNum = pHTInfo->UsbTxAggrNum;
1453         cb_desc         *tcb_desc = (cb_desc *)(skb->cb + MAX_DEV_ADDR_SIZE);
1454         u8              QueueID = tcb_desc->queue_index;
1455
1456         do {
1457                 pSendList->tx_agg_frames[pSendList->nr_drv_agg_frames++] = skb;
1458                 if(pSendList->nr_drv_agg_frames >= nMaxAggrNum) {
1459                         break;
1460                 }
1461
1462         } while((skb = skb_dequeue(&ieee->skb_drv_aggQ[QueueID])));
1463
1464         RT_TRACE(COMP_AMSDU, "DrvAggr_GetAggregatibleList, nAggrTcbNum = %d \n", pSendList->nr_drv_agg_frames);
1465         return pSendList->nr_drv_agg_frames;
1466 }
1467 #endif
1468
1469 static void rtl8192_tx_isr(struct urb *tx_urb)
1470 {
1471         struct sk_buff *skb = (struct sk_buff*)tx_urb->context;
1472         struct net_device *dev = NULL;
1473         struct r8192_priv *priv = NULL;
1474         cb_desc *tcb_desc = (cb_desc *)(skb->cb + MAX_DEV_ADDR_SIZE);
1475         u8  queue_index = tcb_desc->queue_index;
1476 //      bool bToSend0Byte;
1477 //      u16 BufLen = skb->len;
1478
1479         memcpy(&dev,(struct net_device*)(skb->cb),sizeof(struct net_device*));
1480         priv = ieee80211_priv(dev);
1481
1482         if(tcb_desc->queue_index != TXCMD_QUEUE) {
1483                 if(tx_urb->status == 0) {
1484                         dev->trans_start = jiffies;
1485                         // As act as station mode, destion shall be  unicast address.
1486                         //priv->ieee80211->stats.tx_bytes+=(skb->len - priv->ieee80211->tx_headroom);
1487                         //priv->ieee80211->stats.tx_packets++;
1488                         priv->stats.txoktotal++;
1489                         priv->ieee80211->LinkDetectInfo.NumTxOkInPeriod++;
1490                         priv->stats.txbytesunicast += (skb->len - priv->ieee80211->tx_headroom);
1491                 } else {
1492                         priv->ieee80211->stats.tx_errors++;
1493                         //priv->stats.txmanageerr++;
1494                         /* TODO */
1495                 }
1496         }
1497
1498         /* free skb and tx_urb */
1499         if(skb != NULL) {
1500                 dev_kfree_skb_any(skb);
1501                 usb_free_urb(tx_urb);
1502                 atomic_dec(&priv->tx_pending[queue_index]);
1503         }
1504
1505         {
1506                 //
1507                 // Handle HW Beacon:
1508                 // We had transfer our beacon frame to host controler at this moment.
1509                 //
1510                 //
1511                 // Caution:
1512                 // Handling the wait queue of command packets.
1513                 // For Tx command packets, we must not do TCB fragment because it is not handled right now.
1514                 // We must cut the packets to match the size of TX_CMD_PKT before we send it.
1515                 //
1516
1517                 /* Handle MPDU in wait queue. */
1518                 if(queue_index != BEACON_QUEUE) {
1519                         /* Don't send data frame during scanning.*/
1520                         if((skb_queue_len(&priv->ieee80211->skb_waitQ[queue_index]) != 0)&&\
1521                                         (!(priv->ieee80211->queue_stop))) {
1522                                 if(NULL != (skb = skb_dequeue(&(priv->ieee80211->skb_waitQ[queue_index]))))
1523                                         priv->ieee80211->softmac_hard_start_xmit(skb, dev);
1524
1525                                 return; //modified by david to avoid further processing AMSDU
1526                         }
1527 #ifdef USB_TX_DRIVER_AGGREGATION_ENABLE
1528                         else if ((skb_queue_len(&priv->ieee80211->skb_drv_aggQ[queue_index])!= 0)&&\
1529                                 (!(priv->ieee80211->queue_stop))) {
1530                                 // Tx Driver Aggregation process
1531                                 /* The driver will aggregation the packets according to the following stets
1532                                  * 1. check whether there's tx irq available, for it's a completion return
1533                                  *    function, it should contain enough tx irq;
1534                                  * 2. check pakcet type;
1535                                  * 3. intialize sendlist, check whether the to-be send packet no greater than 1
1536                                  * 4. aggregation the packets, and fill firmware info and tx desc to it, etc.
1537                                  * 5. check whehter the packet could be sent, otherwise just insert to wait head
1538                                  * */
1539                                 skb = skb_dequeue(&priv->ieee80211->skb_drv_aggQ[queue_index]);
1540                                 if(!check_nic_enough_desc(dev, queue_index)) {
1541                                         skb_queue_head(&(priv->ieee80211->skb_drv_aggQ[queue_index]), skb);
1542                                         return;
1543                                 }
1544
1545                                 {
1546                                         /*TODO*/
1547                                         /*
1548                                         u8* pHeader = skb->data;
1549
1550                                         if(IsMgntQosData(pHeader) ||
1551                                             IsMgntQData_Ack(pHeader) ||
1552                                             IsMgntQData_Poll(pHeader) ||
1553                                             IsMgntQData_Poll_Ack(pHeader)
1554                                           )
1555                                         */
1556                                         {
1557                                                 struct ieee80211_drv_agg_txb SendList;
1558
1559                                                 memset(&SendList, 0, sizeof(struct ieee80211_drv_agg_txb));
1560                                                 if(DrvAggr_GetAggregatibleList(dev, skb, &SendList) > 1) {
1561                                                         skb = DrvAggr_Aggregation(dev, &SendList);
1562
1563                                                 }
1564                                         }
1565                                         priv->ieee80211->softmac_hard_start_xmit(skb, dev);
1566                                 }
1567                         }
1568 #endif
1569                 }
1570         }
1571
1572 }
1573
1574 void rtl8192_beacon_stop(struct net_device *dev)
1575 {
1576         u8 msr, msrm, msr2;
1577         struct r8192_priv *priv = ieee80211_priv(dev);
1578
1579         msr  = read_nic_byte(dev, MSR);
1580         msrm = msr & MSR_LINK_MASK;
1581         msr2 = msr & ~MSR_LINK_MASK;
1582
1583         if(NIC_8192U == priv->card_8192) {
1584                 usb_kill_urb(priv->rx_urb[MAX_RX_URB]);
1585         }
1586         if ((msrm == (MSR_LINK_ADHOC<<MSR_LINK_SHIFT) ||
1587                 (msrm == (MSR_LINK_MASTER<<MSR_LINK_SHIFT)))){
1588                 write_nic_byte(dev, MSR, msr2 | MSR_LINK_NONE);
1589                 write_nic_byte(dev, MSR, msr);
1590         }
1591 }
1592
1593 void rtl8192_config_rate(struct net_device* dev, u16* rate_config)
1594 {
1595          struct r8192_priv *priv = ieee80211_priv(dev);
1596          struct ieee80211_network *net;
1597          u8 i=0, basic_rate = 0;
1598          net = & priv->ieee80211->current_network;
1599
1600          for (i=0; i<net->rates_len; i++)
1601          {
1602                  basic_rate = net->rates[i]&0x7f;
1603                  switch(basic_rate)
1604                  {
1605                          case MGN_1M:   *rate_config |= RRSR_1M;        break;
1606                          case MGN_2M:   *rate_config |= RRSR_2M;        break;
1607                          case MGN_5_5M: *rate_config |= RRSR_5_5M;      break;
1608                          case MGN_11M:  *rate_config |= RRSR_11M;       break;
1609                          case MGN_6M:   *rate_config |= RRSR_6M;        break;
1610                          case MGN_9M:   *rate_config |= RRSR_9M;        break;
1611                          case MGN_12M:  *rate_config |= RRSR_12M;       break;
1612                          case MGN_18M:  *rate_config |= RRSR_18M;       break;
1613                          case MGN_24M:  *rate_config |= RRSR_24M;       break;
1614                          case MGN_36M:  *rate_config |= RRSR_36M;       break;
1615                          case MGN_48M:  *rate_config |= RRSR_48M;       break;
1616                          case MGN_54M:  *rate_config |= RRSR_54M;       break;
1617                  }
1618          }
1619          for (i=0; i<net->rates_ex_len; i++)
1620          {
1621                  basic_rate = net->rates_ex[i]&0x7f;
1622                  switch(basic_rate)
1623                  {
1624                          case MGN_1M:   *rate_config |= RRSR_1M;        break;
1625                          case MGN_2M:   *rate_config |= RRSR_2M;        break;
1626                          case MGN_5_5M: *rate_config |= RRSR_5_5M;      break;
1627                          case MGN_11M:  *rate_config |= RRSR_11M;       break;
1628                          case MGN_6M:   *rate_config |= RRSR_6M;        break;
1629                          case MGN_9M:   *rate_config |= RRSR_9M;        break;
1630                          case MGN_12M:  *rate_config |= RRSR_12M;       break;
1631                          case MGN_18M:  *rate_config |= RRSR_18M;       break;
1632                          case MGN_24M:  *rate_config |= RRSR_24M;       break;
1633                          case MGN_36M:  *rate_config |= RRSR_36M;       break;
1634                          case MGN_48M:  *rate_config |= RRSR_48M;       break;
1635                          case MGN_54M:  *rate_config |= RRSR_54M;       break;
1636                  }
1637          }
1638 }
1639
1640
1641 #define SHORT_SLOT_TIME 9
1642 #define NON_SHORT_SLOT_TIME 20
1643
1644 void rtl8192_update_cap(struct net_device* dev, u16 cap)
1645 {
1646         u32 tmp = 0;
1647         struct r8192_priv *priv = ieee80211_priv(dev);
1648         struct ieee80211_network *net = &priv->ieee80211->current_network;
1649         priv->short_preamble = cap & WLAN_CAPABILITY_SHORT_PREAMBLE;
1650         tmp = priv->basic_rate;
1651         if (priv->short_preamble)
1652                 tmp |= BRSR_AckShortPmb;
1653         write_nic_dword(dev, RRSR, tmp);
1654
1655         if (net->mode & (IEEE_G|IEEE_N_24G))
1656         {
1657                 u8 slot_time = 0;
1658                 if ((cap & WLAN_CAPABILITY_SHORT_SLOT)&&(!priv->ieee80211->pHTInfo->bCurrentRT2RTLongSlotTime))
1659                 {//short slot time
1660                         slot_time = SHORT_SLOT_TIME;
1661                 }
1662                 else //long slot time
1663                         slot_time = NON_SHORT_SLOT_TIME;
1664                 priv->slot_time = slot_time;
1665                 write_nic_byte(dev, SLOT_TIME, slot_time);
1666         }
1667
1668 }
1669 void rtl8192_net_update(struct net_device *dev)
1670 {
1671
1672         struct r8192_priv *priv = ieee80211_priv(dev);
1673         struct ieee80211_network *net;
1674         u16 BcnTimeCfg = 0, BcnCW = 6, BcnIFS = 0xf;
1675         u16 rate_config = 0;
1676         net = & priv->ieee80211->current_network;
1677
1678         rtl8192_config_rate(dev, &rate_config);
1679         priv->basic_rate = rate_config &= 0x15f;
1680
1681         write_nic_dword(dev,BSSIDR,((u32*)net->bssid)[0]);
1682         write_nic_word(dev,BSSIDR+4,((u16*)net->bssid)[2]);
1683         //for(i=0;i<ETH_ALEN;i++)
1684         //      write_nic_byte(dev,BSSID+i,net->bssid[i]);
1685
1686         rtl8192_update_msr(dev);
1687 //      rtl8192_update_cap(dev, net->capability);
1688         if (priv->ieee80211->iw_mode == IW_MODE_ADHOC)
1689         {
1690         write_nic_word(dev, ATIMWND, 2);
1691         write_nic_word(dev, BCN_DMATIME, 1023);
1692         write_nic_word(dev, BCN_INTERVAL, net->beacon_interval);
1693 //      write_nic_word(dev, BcnIntTime, 100);
1694         write_nic_word(dev, BCN_DRV_EARLY_INT, 1);
1695         write_nic_byte(dev, BCN_ERR_THRESH, 100);
1696                 BcnTimeCfg |= (BcnCW<<BCN_TCFG_CW_SHIFT);
1697         // TODO: BcnIFS may required to be changed on ASIC
1698                 BcnTimeCfg |= BcnIFS<<BCN_TCFG_IFS;
1699
1700         write_nic_word(dev, BCN_TCFG, BcnTimeCfg);
1701         }
1702
1703
1704
1705 }
1706
1707 //temporary hw beacon is not used any more.
1708 //open it when necessary
1709 void rtl819xusb_beacon_tx(struct net_device *dev,u16  tx_rate)
1710 {
1711
1712 }
1713 inline u8 rtl8192_IsWirelessBMode(u16 rate)
1714 {
1715         if( ((rate <= 110) && (rate != 60) && (rate != 90)) || (rate == 220) )
1716                 return 1;
1717         else return 0;
1718 }
1719
1720 u16 N_DBPSOfRate(u16 DataRate);
1721
1722 u16 ComputeTxTime(
1723         u16             FrameLength,
1724         u16             DataRate,
1725         u8              bManagementFrame,
1726         u8              bShortPreamble
1727 )
1728 {
1729         u16     FrameTime;
1730         u16     N_DBPS;
1731         u16     Ceiling;
1732
1733         if( rtl8192_IsWirelessBMode(DataRate) )
1734         {
1735                 if( bManagementFrame || !bShortPreamble || DataRate == 10 )
1736                 {       // long preamble
1737                         FrameTime = (u16)(144+48+(FrameLength*8/(DataRate/10)));
1738                 }
1739                 else
1740                 {       // Short preamble
1741                         FrameTime = (u16)(72+24+(FrameLength*8/(DataRate/10)));
1742                 }
1743                 if( ( FrameLength*8 % (DataRate/10) ) != 0 ) //Get the Ceilling
1744                                 FrameTime ++;
1745         } else {        //802.11g DSSS-OFDM PLCP length field calculation.
1746                 N_DBPS = N_DBPSOfRate(DataRate);
1747                 Ceiling = (16 + 8*FrameLength + 6) / N_DBPS
1748                                 + (((16 + 8*FrameLength + 6) % N_DBPS) ? 1 : 0);
1749                 FrameTime = (u16)(16 + 4 + 4*Ceiling + 6);
1750         }
1751         return FrameTime;
1752 }
1753
1754 u16 N_DBPSOfRate(u16 DataRate)
1755 {
1756          u16 N_DBPS = 24;
1757
1758          switch(DataRate)
1759          {
1760          case 60:
1761           N_DBPS = 24;
1762           break;
1763
1764          case 90:
1765           N_DBPS = 36;
1766           break;
1767
1768          case 120:
1769           N_DBPS = 48;
1770           break;
1771
1772          case 180:
1773           N_DBPS = 72;
1774           break;
1775
1776          case 240:
1777           N_DBPS = 96;
1778           break;
1779
1780          case 360:
1781           N_DBPS = 144;
1782           break;
1783
1784          case 480:
1785           N_DBPS = 192;
1786           break;
1787
1788          case 540:
1789           N_DBPS = 216;
1790           break;
1791
1792          default:
1793           break;
1794          }
1795
1796          return N_DBPS;
1797 }
1798
1799 void rtl819xU_cmd_isr(struct urb *tx_cmd_urb, struct pt_regs *regs)
1800 {
1801         usb_free_urb(tx_cmd_urb);
1802 }
1803
1804 unsigned int txqueue2outpipe(struct r8192_priv* priv,unsigned int tx_queue) {
1805
1806         if(tx_queue >= 9)
1807         {
1808                 RT_TRACE(COMP_ERR,"%s():Unknown queue ID!!!\n",__FUNCTION__);
1809                 return 0x04;
1810         }
1811         return priv->txqueue_to_outpipemap[tx_queue];
1812 }
1813
1814 short rtl819xU_tx_cmd(struct net_device *dev, struct sk_buff *skb)
1815 {
1816         struct r8192_priv *priv = ieee80211_priv(dev);
1817         //u8                    *tx;
1818         int                     status;
1819         struct urb              *tx_urb;
1820         //int                   urb_buf_len;
1821         unsigned int            idx_pipe;
1822         tx_desc_cmd_819x_usb *pdesc = (tx_desc_cmd_819x_usb *)skb->data;
1823         cb_desc *tcb_desc = (cb_desc *)(skb->cb + MAX_DEV_ADDR_SIZE);
1824         u8 queue_index = tcb_desc->queue_index;
1825
1826         //printk("\n %s::queue_index = %d\n",__FUNCTION__, queue_index);
1827         atomic_inc(&priv->tx_pending[queue_index]);
1828         tx_urb = usb_alloc_urb(0,GFP_ATOMIC);
1829         if(!tx_urb){
1830                 dev_kfree_skb(skb);
1831                 return -ENOMEM;
1832         }
1833
1834         memset(pdesc, 0, USB_HWDESC_HEADER_LEN);
1835         /* Tx descriptor ought to be set according to the skb->cb */
1836         pdesc->FirstSeg = 1;//bFirstSeg;
1837         pdesc->LastSeg = 1;//bLastSeg;
1838         pdesc->CmdInit = tcb_desc->bCmdOrInit;
1839         pdesc->TxBufferSize = tcb_desc->txbuf_size;
1840         pdesc->OWN = 1;
1841         pdesc->LINIP = tcb_desc->bLastIniPkt;
1842
1843         //----------------------------------------------------------------------------
1844         // Fill up USB_OUT_CONTEXT.
1845         //----------------------------------------------------------------------------
1846         // Get index to out pipe from specified QueueID.
1847 #ifndef USE_ONE_PIPE
1848         idx_pipe = txqueue2outpipe(priv,queue_index);
1849 #else
1850         idx_pipe = 0x04;
1851 #endif
1852 #ifdef JOHN_DUMP_TXDESC
1853         int i;
1854         printk("<Tx descriptor>--rate %x---",rate);
1855         for (i = 0; i < 8; i++)
1856                 printk("%8x ", tx[i]);
1857         printk("\n");
1858 #endif
1859         usb_fill_bulk_urb(tx_urb,priv->udev, usb_sndbulkpipe(priv->udev,idx_pipe), \
1860                         skb->data, skb->len, rtl8192_tx_isr, skb);
1861
1862         status = usb_submit_urb(tx_urb, GFP_ATOMIC);
1863
1864         if (!status){
1865                 return 0;
1866         }else{
1867                 DMESGE("Error TX CMD URB, error %d",
1868                                 status);
1869                 return -1;
1870         }
1871 }
1872
1873 /*
1874  * Mapping Software/Hardware descriptor queue id to "Queue Select Field"
1875  * in TxFwInfo data structure
1876  * 2006.10.30 by Emily
1877  *
1878  * \param QUEUEID       Software Queue
1879 */
1880 u8 MapHwQueueToFirmwareQueue(u8 QueueID)
1881 {
1882         u8 QueueSelect = 0x0;       //defualt set to
1883
1884         switch(QueueID) {
1885                 case BE_QUEUE:
1886                         QueueSelect = QSLT_BE;  //or QSelect = pTcb->priority;
1887                         break;
1888
1889                 case BK_QUEUE:
1890                         QueueSelect = QSLT_BK;  //or QSelect = pTcb->priority;
1891                         break;
1892
1893                 case VO_QUEUE:
1894                         QueueSelect = QSLT_VO;  //or QSelect = pTcb->priority;
1895                         break;
1896
1897                 case VI_QUEUE:
1898                         QueueSelect = QSLT_VI;  //or QSelect = pTcb->priority;
1899                         break;
1900                 case MGNT_QUEUE:
1901                         QueueSelect = QSLT_MGNT;
1902                         break;
1903
1904                 case BEACON_QUEUE:
1905                         QueueSelect = QSLT_BEACON;
1906                         break;
1907
1908                         // TODO: 2006.10.30 mark other queue selection until we verify it is OK
1909                         // TODO: Remove Assertions
1910 //#if (RTL819X_FPGA_VER & RTL819X_FPGA_GUANGAN_070502)
1911                 case TXCMD_QUEUE:
1912                         QueueSelect = QSLT_CMD;
1913                         break;
1914 //#endif
1915                 case HIGH_QUEUE:
1916                         QueueSelect = QSLT_HIGH;
1917                         break;
1918
1919                 default:
1920                         RT_TRACE(COMP_ERR, "TransmitTCB(): Impossible Queue Selection: %d \n", QueueID);
1921                         break;
1922         }
1923         return QueueSelect;
1924 }
1925
1926 u8 MRateToHwRate8190Pci(u8 rate)
1927 {
1928         u8  ret = DESC90_RATE1M;
1929
1930         switch(rate) {
1931                 case MGN_1M:    ret = DESC90_RATE1M;    break;
1932                 case MGN_2M:    ret = DESC90_RATE2M;    break;
1933                 case MGN_5_5M:  ret = DESC90_RATE5_5M;  break;
1934                 case MGN_11M:   ret = DESC90_RATE11M;   break;
1935                 case MGN_6M:    ret = DESC90_RATE6M;    break;
1936                 case MGN_9M:    ret = DESC90_RATE9M;    break;
1937                 case MGN_12M:   ret = DESC90_RATE12M;   break;
1938                 case MGN_18M:   ret = DESC90_RATE18M;   break;
1939                 case MGN_24M:   ret = DESC90_RATE24M;   break;
1940                 case MGN_36M:   ret = DESC90_RATE36M;   break;
1941                 case MGN_48M:   ret = DESC90_RATE48M;   break;
1942                 case MGN_54M:   ret = DESC90_RATE54M;   break;
1943
1944                 // HT rate since here
1945                 case MGN_MCS0:  ret = DESC90_RATEMCS0;  break;
1946                 case MGN_MCS1:  ret = DESC90_RATEMCS1;  break;
1947                 case MGN_MCS2:  ret = DESC90_RATEMCS2;  break;
1948                 case MGN_MCS3:  ret = DESC90_RATEMCS3;  break;
1949                 case MGN_MCS4:  ret = DESC90_RATEMCS4;  break;
1950                 case MGN_MCS5:  ret = DESC90_RATEMCS5;  break;
1951                 case MGN_MCS6:  ret = DESC90_RATEMCS6;  break;
1952                 case MGN_MCS7:  ret = DESC90_RATEMCS7;  break;
1953                 case MGN_MCS8:  ret = DESC90_RATEMCS8;  break;
1954                 case MGN_MCS9:  ret = DESC90_RATEMCS9;  break;
1955                 case MGN_MCS10: ret = DESC90_RATEMCS10; break;
1956                 case MGN_MCS11: ret = DESC90_RATEMCS11; break;
1957                 case MGN_MCS12: ret = DESC90_RATEMCS12; break;
1958                 case MGN_MCS13: ret = DESC90_RATEMCS13; break;
1959                 case MGN_MCS14: ret = DESC90_RATEMCS14; break;
1960                 case MGN_MCS15: ret = DESC90_RATEMCS15; break;
1961                 case (0x80|0x20): ret = DESC90_RATEMCS32; break;
1962
1963                 default:       break;
1964         }
1965         return ret;
1966 }
1967
1968
1969 u8 QueryIsShort(u8 TxHT, u8 TxRate, cb_desc *tcb_desc)
1970 {
1971         u8   tmp_Short;
1972
1973         tmp_Short = (TxHT==1)?((tcb_desc->bUseShortGI)?1:0):((tcb_desc->bUseShortPreamble)?1:0);
1974
1975         if(TxHT==1 && TxRate != DESC90_RATEMCS15)
1976                 tmp_Short = 0;
1977
1978         return tmp_Short;
1979 }
1980
1981 static void tx_zero_isr(struct urb *tx_urb)
1982 {
1983         return;
1984 }
1985
1986 /*
1987  * The tx procedure is just as following,
1988  * skb->cb will contain all the following information,
1989  * priority, morefrag, rate, &dev.
1990  * */
1991 short rtl8192_tx(struct net_device *dev, struct sk_buff* skb)
1992 {
1993         struct r8192_priv *priv = ieee80211_priv(dev);
1994         cb_desc *tcb_desc = (cb_desc *)(skb->cb + MAX_DEV_ADDR_SIZE);
1995         tx_desc_819x_usb *tx_desc = (tx_desc_819x_usb *)skb->data;
1996         tx_fwinfo_819x_usb *tx_fwinfo = (tx_fwinfo_819x_usb *)(skb->data + USB_HWDESC_HEADER_LEN);
1997         struct usb_device *udev = priv->udev;
1998         int pend;
1999         int status;
2000         struct urb *tx_urb = NULL, *tx_urb_zero = NULL;
2001         //int urb_len;
2002         unsigned int idx_pipe;
2003 //      RT_DEBUG_DATA(COMP_SEND, tcb_desc, sizeof(cb_desc));
2004 //      printk("=============> %s\n", __FUNCTION__);
2005         pend = atomic_read(&priv->tx_pending[tcb_desc->queue_index]);
2006         /* we are locked here so the two atomic_read and inc are executed
2007          * without interleaves
2008          * !!! For debug purpose
2009          */
2010         if( pend > MAX_TX_URB){
2011                 printk("To discard skb packet!\n");
2012                 dev_kfree_skb_any(skb);
2013                 return -1;
2014         }
2015
2016         tx_urb = usb_alloc_urb(0,GFP_ATOMIC);
2017         if(!tx_urb){
2018                 dev_kfree_skb_any(skb);
2019                 return -ENOMEM;
2020         }
2021
2022         /* Fill Tx firmware info */
2023         memset(tx_fwinfo,0,sizeof(tx_fwinfo_819x_usb));
2024         /* DWORD 0 */
2025         tx_fwinfo->TxHT = (tcb_desc->data_rate&0x80)?1:0;
2026         tx_fwinfo->TxRate = MRateToHwRate8190Pci(tcb_desc->data_rate);
2027         tx_fwinfo->EnableCPUDur = tcb_desc->bTxEnableFwCalcDur;
2028         tx_fwinfo->Short = QueryIsShort(tx_fwinfo->TxHT, tx_fwinfo->TxRate, tcb_desc);
2029         if(tcb_desc->bAMPDUEnable) {//AMPDU enabled
2030                 tx_fwinfo->AllowAggregation = 1;
2031                 /* DWORD 1 */
2032                 tx_fwinfo->RxMF = tcb_desc->ampdu_factor;
2033                 tx_fwinfo->RxAMD = tcb_desc->ampdu_density&0x07;//ampdudensity
2034         } else {
2035                 tx_fwinfo->AllowAggregation = 0;
2036                 /* DWORD 1 */
2037                 tx_fwinfo->RxMF = 0;
2038                 tx_fwinfo->RxAMD = 0;
2039         }
2040
2041         /* Protection mode related */
2042         tx_fwinfo->RtsEnable = (tcb_desc->bRTSEnable)?1:0;
2043         tx_fwinfo->CtsEnable = (tcb_desc->bCTSEnable)?1:0;
2044         tx_fwinfo->RtsSTBC = (tcb_desc->bRTSSTBC)?1:0;
2045         tx_fwinfo->RtsHT = (tcb_desc->rts_rate&0x80)?1:0;
2046         tx_fwinfo->RtsRate =  MRateToHwRate8190Pci((u8)tcb_desc->rts_rate);
2047         tx_fwinfo->RtsSubcarrier = (tx_fwinfo->RtsHT==0)?(tcb_desc->RTSSC):0;
2048         tx_fwinfo->RtsBandwidth = (tx_fwinfo->RtsHT==1)?((tcb_desc->bRTSBW)?1:0):0;
2049         tx_fwinfo->RtsShort = (tx_fwinfo->RtsHT==0)?(tcb_desc->bRTSUseShortPreamble?1:0):\
2050                                 (tcb_desc->bRTSUseShortGI?1:0);
2051
2052         /* Set Bandwidth and sub-channel settings. */
2053         if(priv->CurrentChannelBW == HT_CHANNEL_WIDTH_20_40)
2054         {
2055                 if(tcb_desc->bPacketBW) {
2056                         tx_fwinfo->TxBandwidth = 1;
2057                         tx_fwinfo->TxSubCarrier = 0;    //By SD3's Jerry suggestion, use duplicated mode
2058                 } else {
2059                         tx_fwinfo->TxBandwidth = 0;
2060                         tx_fwinfo->TxSubCarrier = priv->nCur40MhzPrimeSC;
2061                 }
2062         } else {
2063                 tx_fwinfo->TxBandwidth = 0;
2064                 tx_fwinfo->TxSubCarrier = 0;
2065         }
2066
2067 #ifdef USB_TX_DRIVER_AGGREGATION_ENABLE
2068         if (tcb_desc->drv_agg_enable)
2069         {
2070                 tx_fwinfo->Tx_INFO_RSVD = (tcb_desc->DrvAggrNum & 0x1f) << 1;
2071         }
2072 #endif
2073         /* Fill Tx descriptor */
2074         memset(tx_desc, 0, sizeof(tx_desc_819x_usb));
2075         /* DWORD 0 */
2076         tx_desc->LINIP = 0;
2077         tx_desc->CmdInit = 1;
2078         tx_desc->Offset =  sizeof(tx_fwinfo_819x_usb) + 8;
2079
2080 #ifdef USB_TX_DRIVER_AGGREGATION_ENABLE
2081         if (tcb_desc->drv_agg_enable) {
2082                 tx_desc->PktSize = tcb_desc->pkt_size;
2083         } else
2084 #endif
2085         {
2086                 tx_desc->PktSize = (skb->len - TX_PACKET_SHIFT_BYTES) & 0xffff;
2087         }
2088
2089         /*DWORD 1*/
2090         tx_desc->SecCAMID= 0;
2091         tx_desc->RATid = tcb_desc->RATRIndex;
2092         {
2093                 //MPDUOverhead = 0;
2094                 tx_desc->NoEnc = 1;
2095         }
2096         tx_desc->SecType = 0x0;
2097                 if (tcb_desc->bHwSec)
2098                         {
2099                                 switch (priv->ieee80211->pairwise_key_type)
2100                                 {
2101                                         case KEY_TYPE_WEP40:
2102                                         case KEY_TYPE_WEP104:
2103                                                  tx_desc->SecType = 0x1;
2104                                                  tx_desc->NoEnc = 0;
2105                                                  break;
2106                                         case KEY_TYPE_TKIP:
2107                                                  tx_desc->SecType = 0x2;
2108                                                  tx_desc->NoEnc = 0;
2109                                                  break;
2110                                         case KEY_TYPE_CCMP:
2111                                                  tx_desc->SecType = 0x3;
2112                                                  tx_desc->NoEnc = 0;
2113                                                  break;
2114                                         case KEY_TYPE_NA:
2115                                                  tx_desc->SecType = 0x0;
2116                                                  tx_desc->NoEnc = 1;
2117                                                  break;
2118                                 }
2119                         }
2120
2121         tx_desc->QueueSelect = MapHwQueueToFirmwareQueue(tcb_desc->queue_index);
2122         tx_desc->TxFWInfoSize =  sizeof(tx_fwinfo_819x_usb);
2123
2124         tx_desc->DISFB = tcb_desc->bTxDisableRateFallBack;
2125         tx_desc->USERATE = tcb_desc->bTxUseDriverAssingedRate;
2126
2127         /* Fill fields that are required to be initialized in all of the descriptors */
2128         //DWORD 0
2129         tx_desc->FirstSeg = 1;
2130         tx_desc->LastSeg = 1;
2131         tx_desc->OWN = 1;
2132
2133 #ifdef USB_TX_DRIVER_AGGREGATION_ENABLE
2134         if (tcb_desc->drv_agg_enable) {
2135                 tx_desc->TxBufferSize = tcb_desc->pkt_size + sizeof(tx_fwinfo_819x_usb);
2136         } else
2137 #endif
2138         {
2139                 //DWORD 2
2140                 tx_desc->TxBufferSize = (u32)(skb->len - USB_HWDESC_HEADER_LEN);
2141         }
2142         /* Get index to out pipe from specified QueueID */
2143 #ifndef USE_ONE_PIPE
2144         idx_pipe = txqueue2outpipe(priv,tcb_desc->queue_index);
2145 #else
2146         idx_pipe = 0x5;
2147 #endif
2148
2149         //RT_DEBUG_DATA(COMP_SEND,tx_fwinfo,sizeof(tx_fwinfo_819x_usb));
2150         //RT_DEBUG_DATA(COMP_SEND,tx_desc,sizeof(tx_desc_819x_usb));
2151
2152         /* To submit bulk urb */
2153         usb_fill_bulk_urb(tx_urb,udev,
2154                         usb_sndbulkpipe(udev,idx_pipe), skb->data,
2155                         skb->len, rtl8192_tx_isr, skb);
2156
2157         status = usb_submit_urb(tx_urb, GFP_ATOMIC);
2158         if (!status){
2159 //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
2160                 bool bSend0Byte = false;
2161                 u8 zero = 0;
2162                 if(udev->speed == USB_SPEED_HIGH)
2163                 {
2164                         if (skb->len > 0 && skb->len % 512 == 0)
2165                                 bSend0Byte = true;
2166                 }
2167                 else
2168                 {
2169                         if (skb->len > 0 && skb->len % 64 == 0)
2170                                 bSend0Byte = true;
2171                 }
2172                 if (bSend0Byte)
2173                 {
2174                         tx_urb_zero = usb_alloc_urb(0,GFP_ATOMIC);
2175                         if(!tx_urb_zero){
2176                                 RT_TRACE(COMP_ERR, "can't alloc urb for zero byte\n");
2177                                 return -ENOMEM;
2178                         }
2179                         usb_fill_bulk_urb(tx_urb_zero,udev,
2180                                         usb_sndbulkpipe(udev,idx_pipe), &zero,
2181                                         0, tx_zero_isr, dev);
2182                         status = usb_submit_urb(tx_urb_zero, GFP_ATOMIC);
2183                         if (status){
2184                         RT_TRACE(COMP_ERR, "Error TX URB for zero byte %d, error %d", atomic_read(&priv->tx_pending[tcb_desc->queue_index]), status);
2185                         return -1;
2186                         }
2187                 }
2188                 dev->trans_start = jiffies;
2189                 atomic_inc(&priv->tx_pending[tcb_desc->queue_index]);
2190                 return 0;
2191         }else{
2192                 RT_TRACE(COMP_ERR, "Error TX URB %d, error %d", atomic_read(&priv->tx_pending[tcb_desc->queue_index]),
2193                                 status);
2194                 return -1;
2195         }
2196 }
2197
2198 short rtl8192_usb_initendpoints(struct net_device *dev)
2199 {
2200         struct r8192_priv *priv = ieee80211_priv(dev);
2201
2202         priv->rx_urb = kmalloc(sizeof(struct urb *) * (MAX_RX_URB+1),
2203                                 GFP_KERNEL);
2204
2205 #ifndef JACKSON_NEW_RX
2206         for(i=0;i<(MAX_RX_URB+1);i++){
2207
2208                 priv->rx_urb[i] = usb_alloc_urb(0,GFP_KERNEL);
2209
2210                 priv->rx_urb[i]->transfer_buffer = kmalloc(RX_URB_SIZE, GFP_KERNEL);
2211
2212                 priv->rx_urb[i]->transfer_buffer_length = RX_URB_SIZE;
2213         }
2214 #endif
2215
2216 #ifdef THOMAS_BEACON
2217 {
2218         long align = 0;
2219         void *oldaddr, *newaddr;
2220
2221         priv->rx_urb[16] = usb_alloc_urb(0, GFP_KERNEL);
2222         priv->oldaddr = kmalloc(16, GFP_KERNEL);
2223         oldaddr = priv->oldaddr;
2224         align = ((long)oldaddr) & 3;
2225         if (align) {
2226                 newaddr = oldaddr + 4 - align;
2227                 priv->rx_urb[16]->transfer_buffer_length = 16 - 4 + align;
2228         } else {
2229                 newaddr = oldaddr;
2230                 priv->rx_urb[16]->transfer_buffer_length = 16;
2231         }
2232         priv->rx_urb[16]->transfer_buffer = newaddr;
2233 }
2234 #endif
2235
2236         memset(priv->rx_urb, 0, sizeof(struct urb*) * MAX_RX_URB);
2237         priv->pp_rxskb = kcalloc(MAX_RX_URB, sizeof(struct sk_buff *),
2238                                  GFP_KERNEL);
2239         if (priv->pp_rxskb == NULL)
2240                 goto destroy;
2241
2242         goto _middle;
2243
2244
2245 destroy:
2246         if (priv->pp_rxskb) {
2247                 kfree(priv->pp_rxskb);
2248         }
2249         if (priv->rx_urb) {
2250                 kfree(priv->rx_urb);
2251         }
2252
2253         priv->pp_rxskb = NULL;
2254         priv->rx_urb = NULL;
2255
2256         DMESGE("Endpoint Alloc Failure");
2257         return -ENOMEM;
2258
2259
2260 _middle:
2261
2262         printk("End of initendpoints\n");
2263         return 0;
2264
2265 }
2266 #ifdef THOMAS_BEACON
2267 void rtl8192_usb_deleteendpoints(struct net_device *dev)
2268 {
2269         int i;
2270         struct r8192_priv *priv = ieee80211_priv(dev);
2271
2272         if(priv->rx_urb){
2273                 for(i=0;i<(MAX_RX_URB+1);i++){
2274                         usb_kill_urb(priv->rx_urb[i]);
2275                         usb_free_urb(priv->rx_urb[i]);
2276                 }
2277                 kfree(priv->rx_urb);
2278                 priv->rx_urb = NULL;
2279         }
2280         if(priv->oldaddr){
2281                 kfree(priv->oldaddr);
2282                 priv->oldaddr = NULL;
2283         }
2284         if (priv->pp_rxskb) {
2285                 kfree(priv->pp_rxskb);
2286                 priv->pp_rxskb = 0;
2287         }
2288 }
2289 #else
2290 void rtl8192_usb_deleteendpoints(struct net_device *dev)
2291 {
2292         int i;
2293         struct r8192_priv *priv = ieee80211_priv(dev);
2294
2295 #ifndef JACKSON_NEW_RX
2296
2297         if(priv->rx_urb){
2298                 for(i=0;i<(MAX_RX_URB+1);i++){
2299                         usb_kill_urb(priv->rx_urb[i]);
2300                         kfree(priv->rx_urb[i]->transfer_buffer);
2301                         usb_free_urb(priv->rx_urb[i]);
2302                 }
2303                 kfree(priv->rx_urb);
2304                 priv->rx_urb = NULL;
2305
2306         }
2307 #else
2308         if(priv->rx_urb){
2309                 kfree(priv->rx_urb);
2310                 priv->rx_urb = NULL;
2311         }
2312         if(priv->oldaddr){
2313                 kfree(priv->oldaddr);
2314                 priv->oldaddr = NULL;
2315         }
2316         if (priv->pp_rxskb) {
2317                 kfree(priv->pp_rxskb);
2318                 priv->pp_rxskb = 0;
2319
2320         }
2321
2322 #endif
2323 }
2324 #endif
2325
2326 extern void rtl8192_update_ratr_table(struct net_device* dev);
2327 void rtl8192_link_change(struct net_device *dev)
2328 {
2329 //      int i;
2330
2331         struct r8192_priv *priv = ieee80211_priv(dev);
2332         struct ieee80211_device* ieee = priv->ieee80211;
2333         //write_nic_word(dev, BCN_INTR_ITV, net->beacon_interval);
2334         if (ieee->state == IEEE80211_LINKED)
2335         {
2336                 rtl8192_net_update(dev);
2337                 rtl8192_update_ratr_table(dev);
2338                 //add this as in pure N mode, wep encryption will use software way, but there is no chance to set this as wep will not set group key in wext. WB.2008.07.08
2339                 if ((KEY_TYPE_WEP40 == ieee->pairwise_key_type) || (KEY_TYPE_WEP104 == ieee->pairwise_key_type))
2340                 EnableHWSecurityConfig8192(dev);
2341         }
2342         /*update timing params*/
2343 //      RT_TRACE(COMP_CH, "========>%s(), chan:%d\n", __FUNCTION__, priv->chan);
2344 //      rtl8192_set_chan(dev, priv->chan);
2345          if (ieee->iw_mode == IW_MODE_INFRA || ieee->iw_mode == IW_MODE_ADHOC)
2346         {
2347                 u32 reg = 0;
2348                 reg = read_nic_dword(dev, RCR);
2349                 if (priv->ieee80211->state == IEEE80211_LINKED)
2350                         priv->ReceiveConfig = reg |= RCR_CBSSID;
2351                 else
2352                         priv->ReceiveConfig = reg &= ~RCR_CBSSID;
2353                 write_nic_dword(dev, RCR, reg);
2354         }
2355
2356 //      rtl8192_set_rxconf(dev);
2357 }
2358
2359 static struct ieee80211_qos_parameters def_qos_parameters = {
2360         {3,3,3,3},/* cw_min */
2361         {7,7,7,7},/* cw_max */
2362         {2,2,2,2},/* aifs */
2363         {0,0,0,0},/* flags */
2364         {0,0,0,0} /* tx_op_limit */
2365 };
2366
2367
2368 void rtl8192_update_beacon(struct work_struct * work)
2369 {
2370         struct r8192_priv *priv = container_of(work, struct r8192_priv, update_beacon_wq.work);
2371         struct net_device *dev = priv->ieee80211->dev;
2372         struct ieee80211_device* ieee = priv->ieee80211;
2373         struct ieee80211_network* net = &ieee->current_network;
2374
2375         if (ieee->pHTInfo->bCurrentHTSupport)
2376                 HTUpdateSelfAndPeerSetting(ieee, net);
2377         ieee->pHTInfo->bCurrentRT2RTLongSlotTime = net->bssht.bdRT2RTLongSlotTime;
2378         rtl8192_update_cap(dev, net->capability);
2379 }
2380 /*
2381 * background support to run QoS activate functionality
2382 */
2383 int WDCAPARA_ADD[] = {EDCAPARA_BE,EDCAPARA_BK,EDCAPARA_VI,EDCAPARA_VO};
2384 void rtl8192_qos_activate(struct work_struct * work)
2385 {
2386         struct r8192_priv *priv = container_of(work, struct r8192_priv, qos_activate);
2387         struct net_device *dev = priv->ieee80211->dev;
2388         struct ieee80211_qos_parameters *qos_parameters = &priv->ieee80211->current_network.qos_data.parameters;
2389         u8 mode = priv->ieee80211->current_network.mode;
2390         //u32 size = sizeof(struct ieee80211_qos_parameters);
2391         u8  u1bAIFS;
2392         u32 u4bAcParam;
2393         int i;
2394
2395         if (priv == NULL)
2396                 return;
2397
2398        mutex_lock(&priv->mutex);
2399         if(priv->ieee80211->state != IEEE80211_LINKED)
2400                 goto success;
2401         RT_TRACE(COMP_QOS,"qos active process with associate response received\n");
2402         /* It better set slot time at first */
2403         /* For we just support b/g mode at present, let the slot time at 9/20 selection */
2404         /* update the ac parameter to related registers */
2405         for(i = 0; i <  QOS_QUEUE_NUM; i++) {
2406                 //Mode G/A: slotTimeTimer = 9; Mode B: 20
2407                 u1bAIFS = qos_parameters->aifs[i] * ((mode&(IEEE_G|IEEE_N_24G)) ?9:20) + aSifsTime;
2408                 u4bAcParam = ((((u32)(qos_parameters->tx_op_limit[i]))<< AC_PARAM_TXOP_LIMIT_OFFSET)|
2409                                 (((u32)(qos_parameters->cw_max[i]))<< AC_PARAM_ECW_MAX_OFFSET)|
2410                                 (((u32)(qos_parameters->cw_min[i]))<< AC_PARAM_ECW_MIN_OFFSET)|
2411                                 ((u32)u1bAIFS << AC_PARAM_AIFS_OFFSET));
2412
2413                 write_nic_dword(dev, WDCAPARA_ADD[i], u4bAcParam);
2414                 //write_nic_dword(dev, WDCAPARA_ADD[i], 0x005e4332);
2415         }
2416
2417 success:
2418        mutex_unlock(&priv->mutex);
2419 }
2420
2421 static int rtl8192_qos_handle_probe_response(struct r8192_priv *priv,
2422                 int active_network,
2423                 struct ieee80211_network *network)
2424 {
2425         int ret = 0;
2426         u32 size = sizeof(struct ieee80211_qos_parameters);
2427
2428         if(priv->ieee80211->state !=IEEE80211_LINKED)
2429                 return ret;
2430
2431         if ((priv->ieee80211->iw_mode != IW_MODE_INFRA))
2432                 return ret;
2433
2434         if (network->flags & NETWORK_HAS_QOS_MASK) {
2435                 if (active_network &&
2436                                 (network->flags & NETWORK_HAS_QOS_PARAMETERS))
2437                         network->qos_data.active = network->qos_data.supported;
2438
2439                 if ((network->qos_data.active == 1) && (active_network == 1) &&
2440                                 (network->flags & NETWORK_HAS_QOS_PARAMETERS) &&
2441                                 (network->qos_data.old_param_count !=
2442                                  network->qos_data.param_count)) {
2443                         network->qos_data.old_param_count =
2444                                 network->qos_data.param_count;
2445                         queue_work(priv->priv_wq, &priv->qos_activate);
2446                         RT_TRACE (COMP_QOS, "QoS parameters change call "
2447                                         "qos_activate\n");
2448                 }
2449         } else {
2450                 memcpy(&priv->ieee80211->current_network.qos_data.parameters,\
2451                        &def_qos_parameters, size);
2452
2453                 if ((network->qos_data.active == 1) && (active_network == 1)) {
2454                         queue_work(priv->priv_wq, &priv->qos_activate);
2455                         RT_TRACE(COMP_QOS, "QoS was disabled call qos_activate \n");
2456                 }
2457                 network->qos_data.active = 0;
2458                 network->qos_data.supported = 0;
2459         }
2460
2461         return 0;
2462 }
2463
2464 /* handle manage frame frame beacon and probe response */
2465 static int rtl8192_handle_beacon(struct net_device * dev,
2466                               struct ieee80211_beacon * beacon,
2467                               struct ieee80211_network * network)
2468 {
2469         struct r8192_priv *priv = ieee80211_priv(dev);
2470
2471         rtl8192_qos_handle_probe_response(priv,1,network);
2472         queue_delayed_work(priv->priv_wq, &priv->update_beacon_wq, 0);
2473         return 0;
2474
2475 }
2476
2477 /*
2478 * handling the beaconing responses. if we get different QoS setting
2479 * off the network from the associated setting, adjust the QoS
2480 * setting
2481 */
2482 static int rtl8192_qos_association_resp(struct r8192_priv *priv,
2483                                     struct ieee80211_network *network)
2484 {
2485         int ret = 0;
2486         unsigned long flags;
2487         u32 size = sizeof(struct ieee80211_qos_parameters);
2488         int set_qos_param = 0;
2489
2490         if ((priv == NULL) || (network == NULL))
2491                 return ret;
2492
2493         if(priv->ieee80211->state !=IEEE80211_LINKED)
2494                 return ret;
2495
2496         if ((priv->ieee80211->iw_mode != IW_MODE_INFRA))
2497                 return ret;
2498
2499         spin_lock_irqsave(&priv->ieee80211->lock, flags);
2500         if(network->flags & NETWORK_HAS_QOS_PARAMETERS) {
2501                 memcpy(&priv->ieee80211->current_network.qos_data.parameters,\
2502                          &network->qos_data.parameters,\
2503                         sizeof(struct ieee80211_qos_parameters));
2504                 priv->ieee80211->current_network.qos_data.active = 1;
2505                  {
2506                         set_qos_param = 1;
2507                         /* update qos parameter for current network */
2508                         priv->ieee80211->current_network.qos_data.old_param_count = \
2509                                  priv->ieee80211->current_network.qos_data.param_count;
2510                         priv->ieee80211->current_network.qos_data.param_count = \
2511                                  network->qos_data.param_count;
2512                 }
2513         } else {
2514                 memcpy(&priv->ieee80211->current_network.qos_data.parameters,\
2515                        &def_qos_parameters, size);
2516                 priv->ieee80211->current_network.qos_data.active = 0;
2517                 priv->ieee80211->current_network.qos_data.supported = 0;
2518                 set_qos_param = 1;
2519         }
2520
2521         spin_unlock_irqrestore(&priv->ieee80211->lock, flags);
2522
2523         RT_TRACE(COMP_QOS, "%s: network->flags = %d,%d\n",__FUNCTION__,network->flags ,priv->ieee80211->current_network.qos_data.active);
2524         if (set_qos_param == 1)
2525                 queue_work(priv->priv_wq, &priv->qos_activate);
2526
2527
2528         return ret;
2529 }
2530
2531
2532 static int rtl8192_handle_assoc_response(struct net_device *dev,
2533                                      struct ieee80211_assoc_response_frame *resp,
2534                                      struct ieee80211_network *network)
2535 {
2536         struct r8192_priv *priv = ieee80211_priv(dev);
2537         rtl8192_qos_association_resp(priv, network);
2538         return 0;
2539 }
2540
2541
2542 void rtl8192_update_ratr_table(struct net_device* dev)
2543         //      POCTET_STRING   posLegacyRate,
2544         //      u8*                     pMcsRate)
2545         //      PRT_WLAN_STA    pEntry)
2546 {
2547         struct r8192_priv* priv = ieee80211_priv(dev);
2548         struct ieee80211_device* ieee = priv->ieee80211;
2549         u8* pMcsRate = ieee->dot11HTOperationalRateSet;
2550         //struct ieee80211_network *net = &ieee->current_network;
2551         u32 ratr_value = 0;
2552         u8 rate_index = 0;
2553         rtl8192_config_rate(dev, (u16*)(&ratr_value));
2554         ratr_value |= (*(u16*)(pMcsRate)) << 12;
2555 //      switch (net->mode)
2556         switch (ieee->mode)
2557         {
2558                 case IEEE_A:
2559                         ratr_value &= 0x00000FF0;
2560                         break;
2561                 case IEEE_B:
2562                         ratr_value &= 0x0000000F;
2563                         break;
2564                 case IEEE_G:
2565                         ratr_value &= 0x00000FF7;
2566                         break;
2567                 case IEEE_N_24G:
2568                 case IEEE_N_5G:
2569                         if (ieee->pHTInfo->PeerMimoPs == 0) //MIMO_PS_STATIC
2570                                 ratr_value &= 0x0007F007;
2571                         else{
2572                                 if (priv->rf_type == RF_1T2R)
2573                                         ratr_value &= 0x000FF007;
2574                                 else
2575                                         ratr_value &= 0x0F81F007;
2576                         }
2577                         break;
2578                 default:
2579                         break;
2580         }
2581         ratr_value &= 0x0FFFFFFF;
2582         if(ieee->pHTInfo->bCurTxBW40MHz && ieee->pHTInfo->bCurShortGI40MHz){
2583                 ratr_value |= 0x80000000;
2584         }else if(!ieee->pHTInfo->bCurTxBW40MHz && ieee->pHTInfo->bCurShortGI20MHz){
2585                 ratr_value |= 0x80000000;
2586         }
2587         write_nic_dword(dev, RATR0+rate_index*4, ratr_value);
2588         write_nic_byte(dev, UFWP, 1);
2589 }
2590
2591 static u8 ccmp_ie[4] = {0x00,0x50,0xf2,0x04};
2592 static u8 ccmp_rsn_ie[4] = {0x00, 0x0f, 0xac, 0x04};
2593 bool GetNmodeSupportBySecCfg8192(struct net_device*dev)
2594 {
2595         struct r8192_priv* priv = ieee80211_priv(dev);
2596         struct ieee80211_device* ieee = priv->ieee80211;
2597         struct ieee80211_network * network = &ieee->current_network;
2598         int wpa_ie_len= ieee->wpa_ie_len;
2599         struct ieee80211_crypt_data* crypt;
2600         int encrypt;
2601
2602         crypt = ieee->crypt[ieee->tx_keyidx];
2603         //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
2604         encrypt = (network->capability & WLAN_CAPABILITY_PRIVACY) || (ieee->host_encrypt && crypt && crypt->ops && (0 == strcmp(crypt->ops->name,"WEP")));
2605
2606         /* simply judge  */
2607         if(encrypt && (wpa_ie_len == 0)) {
2608                 /* wep encryption, no N mode setting */
2609                 return false;
2610 //      } else if((wpa_ie_len != 0)&&(memcmp(&(ieee->wpa_ie[14]),ccmp_ie,4))) {
2611         } else if((wpa_ie_len != 0)) {
2612                 /* parse pairwise key type */
2613                 //if((pairwisekey = WEP40)||(pairwisekey = WEP104)||(pairwisekey = TKIP))
2614                 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))))
2615                         return true;
2616                 else
2617                         return false;
2618         } else {
2619                 return true;
2620         }
2621
2622         return true;
2623 }
2624
2625 bool GetHalfNmodeSupportByAPs819xUsb(struct net_device* dev)
2626 {
2627         bool                    Reval;
2628         struct r8192_priv* priv = ieee80211_priv(dev);
2629         struct ieee80211_device* ieee = priv->ieee80211;
2630
2631         if(ieee->bHalfWirelessN24GMode == true)
2632                 Reval = true;
2633         else
2634                 Reval =  false;
2635
2636         return Reval;
2637 }
2638
2639 void rtl8192_refresh_supportrate(struct r8192_priv* priv)
2640 {
2641         struct ieee80211_device* ieee = priv->ieee80211;
2642         //we donot consider set support rate for ABG mode, only HT MCS rate is set here.
2643         if (ieee->mode == WIRELESS_MODE_N_24G || ieee->mode == WIRELESS_MODE_N_5G)
2644         {
2645                 memcpy(ieee->Regdot11HTOperationalRateSet, ieee->RegHTSuppRateSet, 16);
2646                 //RT_DEBUG_DATA(COMP_INIT, ieee->RegHTSuppRateSet, 16);
2647                 //RT_DEBUG_DATA(COMP_INIT, ieee->Regdot11HTOperationalRateSet, 16);
2648         }
2649         else
2650                 memset(ieee->Regdot11HTOperationalRateSet, 0, 16);
2651         return;
2652 }
2653
2654 u8 rtl8192_getSupportedWireleeMode(struct net_device*dev)
2655 {
2656         struct r8192_priv *priv = ieee80211_priv(dev);
2657         u8 ret = 0;
2658         switch(priv->rf_chip)
2659         {
2660                 case RF_8225:
2661                 case RF_8256:
2662                 case RF_PSEUDO_11N:
2663                         ret = (WIRELESS_MODE_N_24G|WIRELESS_MODE_G|WIRELESS_MODE_B);
2664                         break;
2665                 case RF_8258:
2666                         ret = (WIRELESS_MODE_A|WIRELESS_MODE_N_5G);
2667                         break;
2668                 default:
2669                         ret = WIRELESS_MODE_B;
2670                         break;
2671         }
2672         return ret;
2673 }
2674 void rtl8192_SetWirelessMode(struct net_device* dev, u8 wireless_mode)
2675 {
2676         struct r8192_priv *priv = ieee80211_priv(dev);
2677         u8 bSupportMode = rtl8192_getSupportedWireleeMode(dev);
2678
2679         if ((wireless_mode == WIRELESS_MODE_AUTO) || ((wireless_mode&bSupportMode)==0))
2680         {
2681                 if(bSupportMode & WIRELESS_MODE_N_24G)
2682                 {
2683                         wireless_mode = WIRELESS_MODE_N_24G;
2684                 }
2685                 else if(bSupportMode & WIRELESS_MODE_N_5G)
2686                 {
2687                         wireless_mode = WIRELESS_MODE_N_5G;
2688                 }
2689                 else if((bSupportMode & WIRELESS_MODE_A))
2690                 {
2691                         wireless_mode = WIRELESS_MODE_A;
2692                 }
2693                 else if((bSupportMode & WIRELESS_MODE_G))
2694                 {
2695                         wireless_mode = WIRELESS_MODE_G;
2696                 }
2697                 else if((bSupportMode & WIRELESS_MODE_B))
2698                 {
2699                         wireless_mode = WIRELESS_MODE_B;
2700                 }
2701                 else{
2702                         RT_TRACE(COMP_ERR, "%s(), No valid wireless mode supported, SupportedWirelessMode(%x)!!!\n", __FUNCTION__,bSupportMode);
2703                         wireless_mode = WIRELESS_MODE_B;
2704                 }
2705         }
2706 #ifdef TO_DO_LIST //// TODO: this function doesn't work well at this time, we should wait for FPGA
2707         ActUpdateChannelAccessSetting( pAdapter, pHalData->CurrentWirelessMode, &pAdapter->MgntInfo.Info8185.ChannelAccessSetting );
2708 #endif
2709         priv->ieee80211->mode = wireless_mode;
2710
2711         if ((wireless_mode == WIRELESS_MODE_N_24G) ||  (wireless_mode == WIRELESS_MODE_N_5G))
2712                 priv->ieee80211->pHTInfo->bEnableHT = 1;
2713         else
2714                 priv->ieee80211->pHTInfo->bEnableHT = 0;
2715         RT_TRACE(COMP_INIT, "Current Wireless Mode is %x\n", wireless_mode);
2716         rtl8192_refresh_supportrate(priv);
2717
2718 }
2719 //init priv variables here. only non_zero value should be initialized here.
2720 static void rtl8192_init_priv_variable(struct net_device* dev)
2721 {
2722         struct r8192_priv *priv = ieee80211_priv(dev);
2723         u8 i;
2724         priv->card_8192 = NIC_8192U;
2725         priv->chan = 1; //set to channel 1
2726         priv->ieee80211->mode = WIRELESS_MODE_AUTO; //SET AUTO
2727         priv->ieee80211->iw_mode = IW_MODE_INFRA;
2728         priv->ieee80211->ieee_up=0;
2729         priv->retry_rts = DEFAULT_RETRY_RTS;
2730         priv->retry_data = DEFAULT_RETRY_DATA;
2731         priv->ieee80211->rts = DEFAULT_RTS_THRESHOLD;
2732         priv->ieee80211->rate = 110; //11 mbps
2733         priv->ieee80211->short_slot = 1;
2734         priv->promisc = (dev->flags & IFF_PROMISC) ? 1:0;
2735         priv->CckPwEnl = 6;
2736         //for silent reset
2737         priv->IrpPendingCount = 1;
2738         priv->ResetProgress = RESET_TYPE_NORESET;
2739         priv->bForcedSilentReset = 0;
2740         priv->bDisableNormalResetCheck = false;
2741         priv->force_reset = false;
2742
2743         priv->ieee80211->FwRWRF = 0;    //we don't use FW read/write RF until stable firmware is available.
2744         priv->ieee80211->current_network.beacon_interval = DEFAULT_BEACONINTERVAL;
2745         priv->ieee80211->iw_mode = IW_MODE_INFRA;
2746         priv->ieee80211->softmac_features  = IEEE_SOFTMAC_SCAN |
2747                 IEEE_SOFTMAC_ASSOCIATE | IEEE_SOFTMAC_PROBERQ |
2748                 IEEE_SOFTMAC_PROBERS | IEEE_SOFTMAC_TX_QUEUE |
2749                 IEEE_SOFTMAC_BEACONS;//added by amy 080604 //|  //IEEE_SOFTMAC_SINGLE_QUEUE;
2750
2751         priv->ieee80211->active_scan = 1;
2752         priv->ieee80211->modulation = IEEE80211_CCK_MODULATION | IEEE80211_OFDM_MODULATION;
2753         priv->ieee80211->host_encrypt = 1;
2754         priv->ieee80211->host_decrypt = 1;
2755         priv->ieee80211->start_send_beacons = NULL;//rtl819xusb_beacon_tx;//-by amy 080604
2756         priv->ieee80211->stop_send_beacons = NULL;//rtl8192_beacon_stop;//-by amy 080604
2757         priv->ieee80211->softmac_hard_start_xmit = rtl8192_hard_start_xmit;
2758         priv->ieee80211->set_chan = rtl8192_set_chan;
2759         priv->ieee80211->link_change = rtl8192_link_change;
2760         priv->ieee80211->softmac_data_hard_start_xmit = rtl8192_hard_data_xmit;
2761         priv->ieee80211->data_hard_stop = rtl8192_data_hard_stop;
2762         priv->ieee80211->data_hard_resume = rtl8192_data_hard_resume;
2763         priv->ieee80211->init_wmmparam_flag = 0;
2764         priv->ieee80211->fts = DEFAULT_FRAG_THRESHOLD;
2765         priv->ieee80211->check_nic_enough_desc = check_nic_enough_desc;
2766         priv->ieee80211->tx_headroom = TX_PACKET_SHIFT_BYTES;
2767         priv->ieee80211->qos_support = 1;
2768
2769         //added by WB
2770 //      priv->ieee80211->SwChnlByTimerHandler = rtl8192_phy_SwChnl;
2771         priv->ieee80211->SetBWModeHandler = rtl8192_SetBWMode;
2772         priv->ieee80211->handle_assoc_response = rtl8192_handle_assoc_response;
2773         priv->ieee80211->handle_beacon = rtl8192_handle_beacon;
2774         //added by david
2775         priv->ieee80211->GetNmodeSupportBySecCfg = GetNmodeSupportBySecCfg8192;
2776         priv->ieee80211->GetHalfNmodeSupportByAPsHandler = GetHalfNmodeSupportByAPs819xUsb;
2777         priv->ieee80211->SetWirelessMode = rtl8192_SetWirelessMode;
2778         //added by amy
2779         priv->ieee80211->InitialGainHandler = InitialGain819xUsb;
2780         priv->card_type = USB;
2781 #ifdef TO_DO_LIST
2782         if(Adapter->bInHctTest)
2783         {
2784                 pHalData->ShortRetryLimit = 7;
2785                 pHalData->LongRetryLimit = 7;
2786         }
2787 #endif
2788         {
2789                 priv->ShortRetryLimit = 0x30;
2790                 priv->LongRetryLimit = 0x30;
2791         }
2792         priv->EarlyRxThreshold = 7;
2793         priv->enable_gpio0 = 0;
2794         priv->TransmitConfig =
2795         //      TCR_DurProcMode |       //for RTL8185B, duration setting by HW
2796         //?     TCR_DISReqQsize |
2797                 (TCR_MXDMA_2048<<TCR_MXDMA_OFFSET)|  // Max DMA Burst Size per Tx DMA Burst, 7: reservied.
2798                 (priv->ShortRetryLimit<<TCR_SRL_OFFSET)|        // Short retry limit
2799                 (priv->LongRetryLimit<<TCR_LRL_OFFSET) |        // Long retry limit
2800                 (false ? TCR_SAT: 0);   // FALSE: HW provies PLCP length and LENGEXT, TURE: SW proiveds them
2801 #ifdef TO_DO_LIST
2802         if(Adapter->bInHctTest)
2803                 pHalData->ReceiveConfig =       pHalData->CSMethod |
2804                                                 RCR_AMF | RCR_ADF |     //RCR_AAP |     //accept management/data
2805                                                 //guangan200710
2806                                                 RCR_ACF |       //accept control frame for SW AP needs PS-poll, 2005.07.07, by rcnjko.
2807                                                 RCR_AB | RCR_AM | RCR_APM |             //accept BC/MC/UC
2808                                                 RCR_AICV | RCR_ACRC32 |                 //accept ICV/CRC error packet
2809                                                 ((u32)7<<RCR_MXDMA_OFFSET) | // Max DMA Burst Size per Rx DMA Burst, 7: unlimited.
2810                                                 (pHalData->EarlyRxThreshold<<RCR_FIFO_OFFSET) | // Rx FIFO Threshold, 7: No Rx threshold.
2811                                                 (pHalData->EarlyRxThreshold == 7 ? RCR_OnlyErlPkt:0);
2812         else
2813
2814 #endif
2815         priv->ReceiveConfig     =
2816                 RCR_AMF | RCR_ADF |             //accept management/data
2817                 RCR_ACF |                       //accept control frame for SW AP needs PS-poll, 2005.07.07, by rcnjko.
2818                 RCR_AB | RCR_AM | RCR_APM |     //accept BC/MC/UC
2819                 //RCR_AICV | RCR_ACRC32 |       //accept ICV/CRC error packet
2820                 ((u32)7<<RCR_MXDMA_OFFSET)| // Max DMA Burst Size per Rx DMA Burst, 7: unlimited.
2821                 (priv->EarlyRxThreshold<<RX_FIFO_THRESHOLD_SHIFT) | // Rx FIFO Threshold, 7: No Rx threshold.
2822                 (priv->EarlyRxThreshold == 7 ? RCR_ONLYERLPKT:0);
2823
2824         priv->AcmControl = 0;
2825         priv->pFirmware = kmalloc(sizeof(rt_firmware), GFP_KERNEL);
2826         if (priv->pFirmware)
2827         memset(priv->pFirmware, 0, sizeof(rt_firmware));
2828
2829         /* rx related queue */
2830         skb_queue_head_init(&priv->rx_queue);
2831         skb_queue_head_init(&priv->skb_queue);
2832
2833         /* Tx related queue */
2834         for(i = 0; i < MAX_QUEUE_SIZE; i++) {
2835                 skb_queue_head_init(&priv->ieee80211->skb_waitQ [i]);
2836         }
2837         for(i = 0; i < MAX_QUEUE_SIZE; i++) {
2838                 skb_queue_head_init(&priv->ieee80211->skb_aggQ [i]);
2839         }
2840         for(i = 0; i < MAX_QUEUE_SIZE; i++) {
2841                 skb_queue_head_init(&priv->ieee80211->skb_drv_aggQ [i]);
2842         }
2843         priv->rf_set_chan = rtl8192_phy_SwChnl;
2844 }
2845
2846 //init lock here
2847 static void rtl8192_init_priv_lock(struct r8192_priv* priv)
2848 {
2849         spin_lock_init(&priv->tx_lock);
2850         spin_lock_init(&priv->irq_lock);//added by thomas
2851         //spin_lock_init(&priv->rf_lock);
2852         sema_init(&priv->wx_sem,1);
2853         sema_init(&priv->rf_sem,1);
2854         mutex_init(&priv->mutex);
2855 }
2856
2857 extern  void    rtl819x_watchdog_wqcallback(struct work_struct *work);
2858
2859 void rtl8192_irq_rx_tasklet(struct r8192_priv *priv);
2860 //init tasklet and wait_queue here. only 2.6 above kernel is considered
2861 #define DRV_NAME "wlan0"
2862 static void rtl8192_init_priv_task(struct net_device* dev)
2863 {
2864         struct r8192_priv *priv = ieee80211_priv(dev);
2865
2866 #ifdef PF_SYNCTHREAD
2867         priv->priv_wq = create_workqueue(DRV_NAME,0);
2868 #else
2869         priv->priv_wq = create_workqueue(DRV_NAME);
2870 #endif
2871
2872         INIT_WORK(&priv->reset_wq, rtl8192_restart);
2873
2874         //INIT_DELAYED_WORK(&priv->watch_dog_wq, hal_dm_watchdog);
2875         INIT_DELAYED_WORK(&priv->watch_dog_wq, rtl819x_watchdog_wqcallback);
2876         INIT_DELAYED_WORK(&priv->txpower_tracking_wq,  dm_txpower_trackingcallback);
2877 //      INIT_DELAYED_WORK(&priv->gpio_change_rf_wq,  dm_gpio_change_rf_callback);
2878         INIT_DELAYED_WORK(&priv->rfpath_check_wq,  dm_rf_pathcheck_workitemcallback);
2879         INIT_DELAYED_WORK(&priv->update_beacon_wq, rtl8192_update_beacon);
2880         INIT_DELAYED_WORK(&priv->initialgain_operate_wq, InitialGainOperateWorkItemCallBack);
2881         //INIT_WORK(&priv->SwChnlWorkItem,  rtl8192_SwChnl_WorkItem);
2882         //INIT_WORK(&priv->SetBWModeWorkItem,  rtl8192_SetBWModeWorkItem);
2883         INIT_WORK(&priv->qos_activate, rtl8192_qos_activate);
2884
2885         tasklet_init(&priv->irq_rx_tasklet,
2886              (void(*)(unsigned long))rtl8192_irq_rx_tasklet,
2887              (unsigned long)priv);
2888 }
2889
2890 static void rtl8192_get_eeprom_size(struct net_device* dev)
2891 {
2892         u16 curCR = 0;
2893         struct r8192_priv *priv = ieee80211_priv(dev);
2894         RT_TRACE(COMP_EPROM, "===========>%s()\n", __FUNCTION__);
2895         curCR = read_nic_word_E(dev,EPROM_CMD);
2896         RT_TRACE(COMP_EPROM, "read from Reg EPROM_CMD(%x):%x\n", EPROM_CMD, curCR);
2897         //whether need I consider BIT5?
2898         priv->epromtype = (curCR & Cmd9346CR_9356SEL) ? EPROM_93c56 : EPROM_93c46;
2899         RT_TRACE(COMP_EPROM, "<===========%s(), epromtype:%d\n", __FUNCTION__, priv->epromtype);
2900 }
2901
2902 //used to swap endian. as ntohl & htonl are not neccessary to swap endian, so use this instead.
2903 static inline u16 endian_swap(u16* data)
2904 {
2905         u16 tmp = *data;
2906         *data = (tmp >> 8) | (tmp << 8);
2907         return *data;
2908 }
2909 static void rtl8192_read_eeprom_info(struct net_device* dev)
2910 {
2911         u16 wEPROM_ID = 0;
2912         u8 bMac_Tmp_Addr[6] = {0x00, 0xe0, 0x4c, 0x00, 0x00, 0x02};
2913         u8 bLoad_From_EEPOM = false;
2914         struct r8192_priv *priv = ieee80211_priv(dev);
2915         u16 tmpValue = 0;
2916         RT_TRACE(COMP_EPROM, "===========>%s()\n", __FUNCTION__);
2917         wEPROM_ID = eprom_read(dev, 0); //first read EEPROM ID out;
2918         RT_TRACE(COMP_EPROM, "EEPROM ID is 0x%x\n", wEPROM_ID);
2919
2920         if (wEPROM_ID != RTL8190_EEPROM_ID)
2921         {
2922                 RT_TRACE(COMP_ERR, "EEPROM ID is invalid(is 0x%x(should be 0x%x)\n", wEPROM_ID, RTL8190_EEPROM_ID);
2923         }
2924         else
2925                 bLoad_From_EEPOM = true;
2926
2927         if (bLoad_From_EEPOM)
2928         {
2929                 tmpValue = eprom_read(dev, (EEPROM_VID>>1));
2930                 priv->eeprom_vid = endian_swap(&tmpValue);
2931                 priv->eeprom_pid = eprom_read(dev, (EEPROM_PID>>1));
2932                 tmpValue = eprom_read(dev, (EEPROM_ChannelPlan>>1));
2933                 priv->eeprom_ChannelPlan =((tmpValue&0xff00)>>8);
2934                 priv->btxpowerdata_readfromEEPORM = true;
2935                 priv->eeprom_CustomerID = eprom_read(dev, (EEPROM_Customer_ID>>1)) >>8;
2936         }
2937         else
2938         {
2939                 priv->eeprom_vid = 0;
2940                 priv->eeprom_pid = 0;
2941                 priv->card_8192_version = VERSION_819xU_B;
2942                 priv->eeprom_ChannelPlan = 0;
2943                 priv->eeprom_CustomerID = 0;
2944         }
2945         RT_TRACE(COMP_EPROM, "vid:0x%4x, pid:0x%4x, CustomID:0x%2x, ChanPlan:0x%x\n", priv->eeprom_vid, priv->eeprom_pid, priv->eeprom_CustomerID, priv->eeprom_ChannelPlan);
2946         //set channelplan from eeprom
2947         priv->ChannelPlan = priv->eeprom_ChannelPlan;
2948         if (bLoad_From_EEPOM)
2949         {
2950                 int i;
2951                 for (i=0; i<6; i+=2)
2952                 {
2953                         u16 tmp = 0;
2954                         tmp = eprom_read(dev, (u16)((EEPROM_NODE_ADDRESS_BYTE_0 + i)>>1));
2955                         *(u16*)(&dev->dev_addr[i]) = tmp;
2956                 }
2957         }
2958         else
2959         {
2960                 memcpy(dev->dev_addr, bMac_Tmp_Addr, 6);
2961                 //should I set IDR0 here?
2962         }
2963         RT_TRACE(COMP_EPROM, "MAC addr:%pM\n", dev->dev_addr);
2964         priv->rf_type = RTL819X_DEFAULT_RF_TYPE; //default 1T2R
2965         priv->rf_chip = RF_8256;
2966
2967         if (priv->card_8192_version == (u8)VERSION_819xU_A)
2968         {
2969                 //read Tx power gain offset of legacy OFDM to HT rate
2970                 if (bLoad_From_EEPOM)
2971                         priv->EEPROMTxPowerDiff = (eprom_read(dev, (EEPROM_TxPowerDiff>>1))&0xff00) >> 8;
2972                 else
2973                         priv->EEPROMTxPowerDiff = EEPROM_Default_TxPower;
2974                 RT_TRACE(COMP_EPROM, "TxPowerDiff:%d\n", priv->EEPROMTxPowerDiff);
2975                 //read ThermalMeter from EEPROM
2976                 if (bLoad_From_EEPOM)
2977                         priv->EEPROMThermalMeter = (u8)(eprom_read(dev, (EEPROM_ThermalMeter>>1))&0x00ff);
2978                 else
2979                         priv->EEPROMThermalMeter = EEPROM_Default_ThermalMeter;
2980                 RT_TRACE(COMP_EPROM, "ThermalMeter:%d\n", priv->EEPROMThermalMeter);
2981                 //vivi, for tx power track
2982                 priv->TSSI_13dBm = priv->EEPROMThermalMeter *100;
2983                 //read antenna tx power offset of B/C/D to A from EEPROM
2984                 if (bLoad_From_EEPOM)
2985                         priv->EEPROMPwDiff = (eprom_read(dev, (EEPROM_PwDiff>>1))&0x0f00)>>8;
2986                 else
2987                         priv->EEPROMPwDiff = EEPROM_Default_PwDiff;
2988                 RT_TRACE(COMP_EPROM, "TxPwDiff:%d\n", priv->EEPROMPwDiff);
2989                 // Read CrystalCap from EEPROM
2990                 if (bLoad_From_EEPOM)
2991                         priv->EEPROMCrystalCap = (eprom_read(dev, (EEPROM_CrystalCap>>1))&0x0f);
2992                 else
2993                         priv->EEPROMCrystalCap = EEPROM_Default_CrystalCap;
2994                 RT_TRACE(COMP_EPROM, "CrystalCap = %d\n", priv->EEPROMCrystalCap);
2995                 //get per-channel Tx power level
2996                 if (bLoad_From_EEPOM)
2997                         priv->EEPROM_Def_Ver = (eprom_read(dev, (EEPROM_TxPwIndex_Ver>>1))&0xff00)>>8;
2998                 else
2999                         priv->EEPROM_Def_Ver = 1;
3000                 RT_TRACE(COMP_EPROM, "EEPROM_DEF_VER:%d\n", priv->EEPROM_Def_Ver);
3001                 if (priv->EEPROM_Def_Ver == 0) //old eeprom definition
3002                 {
3003                         int i;
3004                         if (bLoad_From_EEPOM)
3005                                 priv->EEPROMTxPowerLevelCCK = (eprom_read(dev, (EEPROM_TxPwIndex_CCK>>1))&0xff) >> 8;
3006                         else
3007                                 priv->EEPROMTxPowerLevelCCK = 0x10;
3008                         RT_TRACE(COMP_EPROM, "CCK Tx Power Levl: 0x%02x\n", priv->EEPROMTxPowerLevelCCK);
3009                         for (i=0; i<3; i++)
3010                         {
3011                                 if (bLoad_From_EEPOM)
3012                                 {
3013                                         tmpValue = eprom_read(dev, (EEPROM_TxPwIndex_OFDM_24G+i)>>1);
3014                                         if (((EEPROM_TxPwIndex_OFDM_24G+i) % 2) == 0)
3015                                                 tmpValue = tmpValue & 0x00ff;
3016                                         else
3017                                                 tmpValue = (tmpValue & 0xff00) >> 8;
3018                                 }
3019                                 else
3020                                         tmpValue = 0x10;
3021                                 priv->EEPROMTxPowerLevelOFDM24G[i] = (u8) tmpValue;
3022                                 RT_TRACE(COMP_EPROM, "OFDM 2.4G Tx Power Level, Index %d = 0x%02x\n", i, priv->EEPROMTxPowerLevelCCK);
3023                         }
3024                 }//end if EEPROM_DEF_VER == 0
3025                 else if (priv->EEPROM_Def_Ver == 1)
3026                 {
3027                         if (bLoad_From_EEPOM)
3028                         {
3029                                 tmpValue = eprom_read(dev, (EEPROM_TxPwIndex_CCK_V1>>1));
3030                                 tmpValue = (tmpValue & 0xff00) >> 8;
3031                         }
3032                         else
3033                                 tmpValue = 0x10;
3034                         priv->EEPROMTxPowerLevelCCK_V1[0] = (u8)tmpValue;
3035
3036                         if (bLoad_From_EEPOM)
3037                                 tmpValue = eprom_read(dev, (EEPROM_TxPwIndex_CCK_V1 + 2)>>1);
3038                         else
3039                                 tmpValue = 0x1010;
3040                         *((u16*)(&priv->EEPROMTxPowerLevelCCK_V1[1])) = tmpValue;
3041                         if (bLoad_From_EEPOM)
3042                                 tmpValue = eprom_read(dev, (EEPROM_TxPwIndex_OFDM_24G_V1>>1));
3043                         else
3044                                 tmpValue = 0x1010;
3045                         *((u16*)(&priv->EEPROMTxPowerLevelOFDM24G[0])) = tmpValue;
3046                         if (bLoad_From_EEPOM)
3047                                 tmpValue = eprom_read(dev, (EEPROM_TxPwIndex_OFDM_24G_V1+2)>>1);
3048                         else
3049                                 tmpValue = 0x10;
3050                         priv->EEPROMTxPowerLevelOFDM24G[2] = (u8)tmpValue;
3051                 }//endif EEPROM_Def_Ver == 1
3052
3053                 //update HAL variables
3054                 //
3055                 {
3056                         int i;
3057                         for (i=0; i<14; i++)
3058                         {
3059                                 if (i<=3)
3060                                         priv->TxPowerLevelOFDM24G[i] = priv->EEPROMTxPowerLevelOFDM24G[0];
3061                                 else if (i>=4 && i<=9)
3062                                         priv->TxPowerLevelOFDM24G[i] = priv->EEPROMTxPowerLevelOFDM24G[1];
3063                                 else
3064                                         priv->TxPowerLevelOFDM24G[i] = priv->EEPROMTxPowerLevelOFDM24G[2];
3065                         }
3066
3067                         for (i=0; i<14; i++)
3068                         {
3069                                 if (priv->EEPROM_Def_Ver == 0)
3070                                 {
3071                                         if (i<=3)
3072                                                 priv->TxPowerLevelCCK[i] = priv->EEPROMTxPowerLevelOFDM24G[0] + (priv->EEPROMTxPowerLevelCCK - priv->EEPROMTxPowerLevelOFDM24G[1]);
3073                                         else if (i>=4 && i<=9)
3074                                                 priv->TxPowerLevelCCK[i] = priv->EEPROMTxPowerLevelCCK;
3075                                         else
3076                                                 priv->TxPowerLevelCCK[i] = priv->EEPROMTxPowerLevelOFDM24G[2] + (priv->EEPROMTxPowerLevelCCK - priv->EEPROMTxPowerLevelOFDM24G[1]);
3077                                 }
3078                                 else if (priv->EEPROM_Def_Ver == 1)
3079                                 {
3080                                         if (i<=3)
3081                                                 priv->TxPowerLevelCCK[i] = priv->EEPROMTxPowerLevelCCK_V1[0];
3082                                         else if (i>=4 && i<=9)
3083                                                 priv->TxPowerLevelCCK[i] = priv->EEPROMTxPowerLevelCCK_V1[1];
3084                                         else
3085                                                 priv->TxPowerLevelCCK[i] = priv->EEPROMTxPowerLevelCCK_V1[2];
3086                                 }
3087                         }
3088                 }//end update HAL variables
3089                 priv->TxPowerDiff = priv->EEPROMPwDiff;
3090 // Antenna B gain offset to antenna A, bit0~3
3091                 priv->AntennaTxPwDiff[0] = (priv->EEPROMTxPowerDiff & 0xf);
3092                 // Antenna C gain offset to antenna A, bit4~7
3093                 priv->AntennaTxPwDiff[1] = ((priv->EEPROMTxPowerDiff & 0xf0)>>4);
3094                 // CrystalCap, bit12~15
3095                 priv->CrystalCap = priv->EEPROMCrystalCap;
3096                 // ThermalMeter, bit0~3 for RFIC1, bit4~7 for RFIC2
3097                 // 92U does not enable TX power tracking.
3098                 priv->ThermalMeter[0] = priv->EEPROMThermalMeter;
3099         }//end if VersionID == VERSION_819xU_A
3100
3101 //added by vivi, for dlink led, 20080416
3102         switch(priv->eeprom_CustomerID)
3103         {
3104                 case EEPROM_CID_RUNTOP:
3105                         priv->CustomerID = RT_CID_819x_RUNTOP;
3106                         break;
3107
3108                 case EEPROM_CID_DLINK:
3109                         priv->CustomerID = RT_CID_DLINK;
3110                         break;
3111
3112                 default:
3113                         priv->CustomerID = RT_CID_DEFAULT;
3114                         break;
3115
3116         }
3117
3118         switch(priv->CustomerID)
3119         {
3120                 case RT_CID_819x_RUNTOP:
3121                         priv->LedStrategy = SW_LED_MODE2;
3122                         break;
3123
3124                 case RT_CID_DLINK:
3125                         priv->LedStrategy = SW_LED_MODE4;
3126                         break;
3127
3128                 default:
3129                         priv->LedStrategy = SW_LED_MODE0;
3130                         break;
3131
3132         }
3133
3134
3135         if(priv->rf_type == RF_1T2R)
3136         {
3137                 RT_TRACE(COMP_EPROM, "\n1T2R config\n");
3138         }
3139         else
3140         {
3141                 RT_TRACE(COMP_EPROM, "\n2T4R config\n");
3142         }
3143
3144         // 2008/01/16 MH We can only know RF type in the function. So we have to init
3145         // DIG RATR table again.
3146         init_rate_adaptive(dev);
3147         //we need init DIG RATR table here again.
3148
3149         RT_TRACE(COMP_EPROM, "<===========%s()\n", __FUNCTION__);
3150         return;
3151 }
3152
3153 short rtl8192_get_channel_map(struct net_device * dev)
3154 {
3155         struct r8192_priv *priv = ieee80211_priv(dev);
3156 #ifdef ENABLE_DOT11D
3157         if(priv->ChannelPlan > COUNTRY_CODE_GLOBAL_DOMAIN){
3158                 printk("rtl8180_init:Error channel plan! Set to default.\n");
3159                 priv->ChannelPlan= 0;
3160         }
3161         RT_TRACE(COMP_INIT, "Channel plan is %d\n",priv->ChannelPlan);
3162
3163         rtl819x_set_channel_map(priv->ChannelPlan, priv);
3164 #else
3165         int ch,i;
3166         //Set Default Channel Plan
3167         if(!channels){
3168                 DMESG("No channels, aborting");
3169                 return -1;
3170         }
3171         ch=channels;
3172         priv->ChannelPlan= 0;//hikaru
3173          // set channels 1..14 allowed in given locale
3174         for (i=1; i<=14; i++) {
3175                 (priv->ieee80211->channel_map)[i] = (u8)(ch & 0x01);
3176                 ch >>= 1;
3177         }
3178 #endif
3179         return 0;
3180 }
3181
3182 short rtl8192_init(struct net_device *dev)
3183 {
3184
3185         struct r8192_priv *priv = ieee80211_priv(dev);
3186
3187         memset(&(priv->stats),0,sizeof(struct Stats));
3188         memset(priv->txqueue_to_outpipemap,0,9);
3189 #ifdef PIPE12
3190         {
3191                 int i=0;
3192                 u8 queuetopipe[]={3,2,1,0,4,8,7,6,5};
3193                 memcpy(priv->txqueue_to_outpipemap,queuetopipe,9);
3194 /*              for(i=0;i<9;i++)
3195                         printk("%d ",priv->txqueue_to_outpipemap[i]);
3196                 printk("\n");*/
3197         }
3198 #else
3199         {
3200                 u8 queuetopipe[]={3,2,1,0,4,4,0,4,4};
3201                 memcpy(priv->txqueue_to_outpipemap,queuetopipe,9);
3202 /*              for(i=0;i<9;i++)
3203                         printk("%d ",priv->txqueue_to_outpipemap[i]);
3204                 printk("\n");*/
3205         }
3206 #endif
3207         rtl8192_init_priv_variable(dev);
3208         rtl8192_init_priv_lock(priv);
3209         rtl8192_init_priv_task(dev);
3210         rtl8192_get_eeprom_size(dev);
3211         rtl8192_read_eeprom_info(dev);
3212         rtl8192_get_channel_map(dev);
3213         init_hal_dm(dev);
3214         init_timer(&priv->watch_dog_timer);
3215         priv->watch_dog_timer.data = (unsigned long)dev;
3216         priv->watch_dog_timer.function = watch_dog_timer_callback;
3217         if(rtl8192_usb_initendpoints(dev)!=0){
3218                 DMESG("Endopoints initialization failed");
3219                 return -ENOMEM;
3220         }
3221
3222         //rtl8192_adapter_start(dev);
3223 #ifdef DEBUG_EPROM
3224         dump_eprom(dev);
3225 #endif
3226         return 0;
3227 }
3228
3229 /******************************************************************************
3230  *function:  This function actually only set RRSR, RATR and BW_OPMODE registers
3231  *           not to do all the hw config as its name says
3232  *   input:  net_device dev
3233  *  output:  none
3234  *  return:  none
3235  *  notice:  This part need to modified according to the rate set we filtered
3236  * ****************************************************************************/
3237 void rtl8192_hwconfig(struct net_device* dev)
3238 {
3239         u32 regRATR = 0, regRRSR = 0;
3240         u8 regBwOpMode = 0, regTmp = 0;
3241         struct r8192_priv *priv = ieee80211_priv(dev);
3242
3243 // Set RRSR, RATR, and BW_OPMODE registers
3244         //
3245         switch(priv->ieee80211->mode)
3246         {
3247         case WIRELESS_MODE_B:
3248                 regBwOpMode = BW_OPMODE_20MHZ;
3249                 regRATR = RATE_ALL_CCK;
3250                 regRRSR = RATE_ALL_CCK;
3251                 break;
3252         case WIRELESS_MODE_A:
3253                 regBwOpMode = BW_OPMODE_5G |BW_OPMODE_20MHZ;
3254                 regRATR = RATE_ALL_OFDM_AG;
3255                 regRRSR = RATE_ALL_OFDM_AG;
3256                 break;
3257         case WIRELESS_MODE_G:
3258                 regBwOpMode = BW_OPMODE_20MHZ;
3259                 regRATR = RATE_ALL_CCK | RATE_ALL_OFDM_AG;
3260                 regRRSR = RATE_ALL_CCK | RATE_ALL_OFDM_AG;
3261                 break;
3262         case WIRELESS_MODE_AUTO:
3263 #ifdef TO_DO_LIST
3264                 if (Adapter->bInHctTest)
3265                 {
3266                     regBwOpMode = BW_OPMODE_20MHZ;
3267                     regRATR = RATE_ALL_CCK | RATE_ALL_OFDM_AG;
3268                     regRRSR = RATE_ALL_CCK | RATE_ALL_OFDM_AG;
3269                 }
3270                 else
3271 #endif
3272                 {
3273                     regBwOpMode = BW_OPMODE_20MHZ;
3274                     regRATR = RATE_ALL_CCK | RATE_ALL_OFDM_AG | RATE_ALL_OFDM_1SS | RATE_ALL_OFDM_2SS;
3275                     regRRSR = RATE_ALL_CCK | RATE_ALL_OFDM_AG;
3276                 }
3277                 break;
3278         case WIRELESS_MODE_N_24G:
3279                 // It support CCK rate by default.
3280                 // CCK rate will be filtered out only when associated AP does not support it.
3281                 regBwOpMode = BW_OPMODE_20MHZ;
3282                         regRATR = RATE_ALL_CCK | RATE_ALL_OFDM_AG | RATE_ALL_OFDM_1SS | RATE_ALL_OFDM_2SS;
3283                         regRRSR = RATE_ALL_CCK | RATE_ALL_OFDM_AG;
3284                 break;
3285         case WIRELESS_MODE_N_5G:
3286                 regBwOpMode = BW_OPMODE_5G;
3287                 regRATR = RATE_ALL_OFDM_AG | RATE_ALL_OFDM_1SS | RATE_ALL_OFDM_2SS;
3288                 regRRSR = RATE_ALL_OFDM_AG;
3289                 break;
3290         }
3291
3292         write_nic_byte(dev, BW_OPMODE, regBwOpMode);
3293         {
3294                 u32 ratr_value = 0;
3295                 ratr_value = regRATR;
3296                 if (priv->rf_type == RF_1T2R)
3297                 {
3298                         ratr_value &= ~(RATE_ALL_OFDM_2SS);
3299                 }
3300                 write_nic_dword(dev, RATR0, ratr_value);
3301                 write_nic_byte(dev, UFWP, 1);
3302         }
3303         regTmp = read_nic_byte(dev, 0x313);
3304         regRRSR = ((regTmp) << 24) | (regRRSR & 0x00ffffff);
3305         write_nic_dword(dev, RRSR, regRRSR);
3306
3307         //
3308         // Set Retry Limit here
3309         //
3310         write_nic_word(dev, RETRY_LIMIT,
3311                         priv->ShortRetryLimit << RETRY_LIMIT_SHORT_SHIFT | \
3312                         priv->LongRetryLimit << RETRY_LIMIT_LONG_SHIFT);
3313         // Set Contention Window here
3314
3315         // Set Tx AGC
3316
3317         // Set Tx Antenna including Feedback control
3318
3319         // Set Auto Rate fallback control
3320
3321
3322 }
3323
3324
3325 //InitializeAdapter and PhyCfg
3326 bool rtl8192_adapter_start(struct net_device *dev)
3327 {
3328         struct r8192_priv *priv = ieee80211_priv(dev);
3329         u32 dwRegRead = 0;
3330         bool init_status = true;
3331         RT_TRACE(COMP_INIT, "====>%s()\n", __FUNCTION__);
3332         priv->Rf_Mode = RF_OP_By_SW_3wire;
3333         //for ASIC power on sequence
3334         write_nic_byte_E(dev, 0x5f, 0x80);
3335         mdelay(50);
3336         write_nic_byte_E(dev, 0x5f, 0xf0);
3337         write_nic_byte_E(dev, 0x5d, 0x00);
3338         write_nic_byte_E(dev, 0x5e, 0x80);
3339         write_nic_byte(dev, 0x17, 0x37);
3340         mdelay(10);
3341 //#ifdef TO_DO_LIST
3342         priv->pFirmware->firmware_status = FW_STATUS_0_INIT;
3343         //config CPUReset Register
3344         //Firmware Reset or not?
3345         dwRegRead = read_nic_dword(dev, CPU_GEN);
3346         if (priv->pFirmware->firmware_status == FW_STATUS_0_INIT)
3347                 dwRegRead |= CPU_GEN_SYSTEM_RESET; //do nothing here?
3348         else if (priv->pFirmware->firmware_status == FW_STATUS_5_READY)
3349                 dwRegRead |= CPU_GEN_FIRMWARE_RESET;
3350         else
3351                 RT_TRACE(COMP_ERR, "ERROR in %s(): undefined firmware state(%d)\n", __FUNCTION__,   priv->pFirmware->firmware_status);
3352
3353         write_nic_dword(dev, CPU_GEN, dwRegRead);
3354         //mdelay(30);
3355         //config BB.
3356         rtl8192_BBConfig(dev);
3357
3358         //Loopback mode or not
3359         priv->LoopbackMode = RTL819xU_NO_LOOPBACK;
3360 //      priv->LoopbackMode = RTL819xU_MAC_LOOPBACK;
3361
3362         dwRegRead = read_nic_dword(dev, CPU_GEN);
3363         if (priv->LoopbackMode == RTL819xU_NO_LOOPBACK)
3364                 dwRegRead = ((dwRegRead & CPU_GEN_NO_LOOPBACK_MSK) | CPU_GEN_NO_LOOPBACK_SET);
3365         else if (priv->LoopbackMode == RTL819xU_MAC_LOOPBACK)
3366                 dwRegRead |= CPU_CCK_LOOPBACK;
3367         else
3368                 RT_TRACE(COMP_ERR, "Serious error in %s(): wrong loopback mode setting(%d)\n", __FUNCTION__,  priv->LoopbackMode);
3369
3370         write_nic_dword(dev, CPU_GEN, dwRegRead);
3371
3372         //after reset cpu, we need wait for a seconds to write in register.
3373         udelay(500);
3374
3375         //xiong add for new bitfile:usb suspend reset pin set to 1. //do we need?
3376         write_nic_byte_E(dev, 0x5f, (read_nic_byte_E(dev, 0x5f)|0x20));
3377
3378         //Set Hardware
3379         rtl8192_hwconfig(dev);
3380
3381         //turn on Tx/Rx
3382         write_nic_byte(dev, CMDR, CR_RE|CR_TE);
3383
3384         //set IDR0 here
3385         write_nic_dword(dev, MAC0, ((u32*)dev->dev_addr)[0]);
3386         write_nic_word(dev, MAC4, ((u16*)(dev->dev_addr + 4))[0]);
3387
3388         //set RCR
3389         write_nic_dword(dev, RCR, priv->ReceiveConfig);
3390
3391         //Initialize Number of Reserved Pages in Firmware Queue
3392         write_nic_dword(dev, RQPN1,  NUM_OF_PAGE_IN_FW_QUEUE_BK << RSVD_FW_QUEUE_PAGE_BK_SHIFT |\
3393                                                 NUM_OF_PAGE_IN_FW_QUEUE_BE << RSVD_FW_QUEUE_PAGE_BE_SHIFT | \
3394                                                 NUM_OF_PAGE_IN_FW_QUEUE_VI << RSVD_FW_QUEUE_PAGE_VI_SHIFT | \
3395                                                 NUM_OF_PAGE_IN_FW_QUEUE_VO <<RSVD_FW_QUEUE_PAGE_VO_SHIFT);
3396         write_nic_dword(dev, RQPN2, NUM_OF_PAGE_IN_FW_QUEUE_MGNT << RSVD_FW_QUEUE_PAGE_MGNT_SHIFT |\
3397                                                 NUM_OF_PAGE_IN_FW_QUEUE_CMD << RSVD_FW_QUEUE_PAGE_CMD_SHIFT);
3398         write_nic_dword(dev, RQPN3, APPLIED_RESERVED_QUEUE_IN_FW| \
3399                                                 NUM_OF_PAGE_IN_FW_QUEUE_BCN<<RSVD_FW_QUEUE_PAGE_BCN_SHIFT
3400 //                                              | NUM_OF_PAGE_IN_FW_QUEUE_PUB<<RSVD_FW_QUEUE_PAGE_PUB_SHIFT
3401                                                 );
3402         write_nic_dword(dev, RATR0+4*7, (RATE_ALL_OFDM_AG | RATE_ALL_CCK));
3403
3404         //Set AckTimeout
3405         // TODO: (it value is only for FPGA version). need to be changed!!2006.12.18, by Emily
3406         write_nic_byte(dev, ACK_TIMEOUT, 0x30);
3407
3408 //      RT_TRACE(COMP_INIT, "%s():priv->ResetProgress is %d\n", __FUNCTION__,priv->ResetProgress);
3409         if(priv->ResetProgress == RESET_TYPE_NORESET)
3410         rtl8192_SetWirelessMode(dev, priv->ieee80211->mode);
3411         if(priv->ResetProgress == RESET_TYPE_NORESET){
3412         CamResetAllEntry(dev);
3413         {
3414                 u8 SECR_value = 0x0;
3415                 SECR_value |= SCR_TxEncEnable;
3416                 SECR_value |= SCR_RxDecEnable;
3417                 SECR_value |= SCR_NoSKMC;
3418                 write_nic_byte(dev, SECR, SECR_value);
3419         }
3420         }
3421
3422         //Beacon related
3423         write_nic_word(dev, ATIMWND, 2);
3424         write_nic_word(dev, BCN_INTERVAL, 100);
3425
3426         {
3427 #define DEFAULT_EDCA 0x005e4332
3428                 int i;
3429                 for (i=0; i<QOS_QUEUE_NUM; i++)
3430                 write_nic_dword(dev, WDCAPARA_ADD[i], DEFAULT_EDCA);
3431         }
3432 #ifdef USB_RX_AGGREGATION_SUPPORT
3433         //3 For usb rx firmware aggregation control
3434         if(priv->ResetProgress == RESET_TYPE_NORESET)
3435         {
3436                 u32 ulValue;
3437                 PRT_HIGH_THROUGHPUT     pHTInfo = priv->ieee80211->pHTInfo;
3438                 ulValue = (pHTInfo->UsbRxFwAggrEn<<24) | (pHTInfo->UsbRxFwAggrPageNum<<16) |
3439                                         (pHTInfo->UsbRxFwAggrPacketNum<<8) | (pHTInfo->UsbRxFwAggrTimeout);
3440                 /*
3441                  * If usb rx firmware aggregation is enabled,
3442                  * when anyone of three threshold conditions above is reached,
3443                  * firmware will send aggregated packet to driver.
3444                  */
3445                 write_nic_dword(dev, 0x1a8, ulValue);
3446                 priv->bCurrentRxAggrEnable = true;
3447         }
3448 #endif
3449
3450         rtl8192_phy_configmac(dev);
3451
3452         if (priv->card_8192_version == (u8) VERSION_819xU_A)
3453         {
3454                 rtl8192_phy_getTxPower(dev);
3455                 rtl8192_phy_setTxPower(dev, priv->chan);
3456         }
3457
3458         //Firmware download
3459         init_status = init_firmware(dev);
3460         if(!init_status)
3461         {
3462                 RT_TRACE(COMP_ERR,"ERR!!! %s(): Firmware download is failed\n", __FUNCTION__);
3463                 return init_status;
3464         }
3465         RT_TRACE(COMP_INIT, "%s():after firmware download\n", __FUNCTION__);
3466         //
3467 #ifdef TO_DO_LIST
3468 if(Adapter->ResetProgress == RESET_TYPE_NORESET)
3469         {
3470                 if(pMgntInfo->RegRfOff == TRUE)
3471                 { // User disable RF via registry.
3472                         RT_TRACE((COMP_INIT|COMP_RF), DBG_LOUD, ("InitializeAdapter819xUsb(): Turn off RF for RegRfOff ----------\n"));
3473                         MgntActSet_RF_State(Adapter, eRfOff, RF_CHANGE_BY_SW);
3474                         // Those action will be discard in MgntActSet_RF_State because off the same state
3475                         for(eRFPath = 0; eRFPath <pHalData->NumTotalRFPath; eRFPath++)
3476                                 PHY_SetRFReg(Adapter, (RF90_RADIO_PATH_E)eRFPath, 0x4, 0xC00, 0x0);
3477                 }
3478                 else if(pMgntInfo->RfOffReason > RF_CHANGE_BY_PS)
3479                 { // H/W or S/W RF OFF before sleep.
3480                         RT_TRACE((COMP_INIT|COMP_RF), DBG_LOUD, ("InitializeAdapter819xUsb(): Turn off RF for RfOffReason(%d) ----------\n", pMgntInfo->RfOffReason));
3481                         MgntActSet_RF_State(Adapter, eRfOff, pMgntInfo->RfOffReason);
3482                 }
3483                 else
3484                 {
3485                         pHalData->eRFPowerState = eRfOn;
3486                         pMgntInfo->RfOffReason = 0;
3487                         RT_TRACE((COMP_INIT|COMP_RF), DBG_LOUD, ("InitializeAdapter819xUsb(): RF is on ----------\n"));
3488                 }
3489         }
3490         else
3491         {
3492                 if(pHalData->eRFPowerState == eRfOff)
3493                 {
3494                         MgntActSet_RF_State(Adapter, eRfOff, pMgntInfo->RfOffReason);
3495                         // Those action will be discard in MgntActSet_RF_State because off the same state
3496                         for(eRFPath = 0; eRFPath <pHalData->NumTotalRFPath; eRFPath++)
3497                                 PHY_SetRFReg(Adapter, (RF90_RADIO_PATH_E)eRFPath, 0x4, 0xC00, 0x0);
3498                 }
3499         }
3500 #endif
3501         //config RF.
3502         if(priv->ResetProgress == RESET_TYPE_NORESET){
3503         rtl8192_phy_RFConfig(dev);
3504         RT_TRACE(COMP_INIT, "%s():after phy RF config\n", __FUNCTION__);
3505         }
3506
3507
3508         if(priv->ieee80211->FwRWRF)
3509                 // We can force firmware to do RF-R/W
3510                 priv->Rf_Mode = RF_OP_By_FW;
3511         else
3512                 priv->Rf_Mode = RF_OP_By_SW_3wire;
3513
3514
3515         rtl8192_phy_updateInitGain(dev);
3516         /*--set CCK and OFDM Block "ON"--*/
3517         rtl8192_setBBreg(dev, rFPGA0_RFMOD, bCCKEn, 0x1);
3518         rtl8192_setBBreg(dev, rFPGA0_RFMOD, bOFDMEn, 0x1);
3519
3520         if(priv->ResetProgress == RESET_TYPE_NORESET)
3521         {
3522                 //if D or C cut
3523                 u8 tmpvalue = read_nic_byte(dev, 0x301);
3524                 if(tmpvalue ==0x03)
3525                 {
3526                         priv->bDcut = TRUE;
3527                         RT_TRACE(COMP_POWER_TRACKING, "D-cut\n");
3528                 }
3529                 else
3530                 {
3531                         priv->bDcut = FALSE;
3532                         RT_TRACE(COMP_POWER_TRACKING, "C-cut\n");
3533                 }
3534                 dm_initialize_txpower_tracking(dev);
3535
3536                 if(priv->bDcut == TRUE)
3537                 {
3538                         u32 i, TempCCk;
3539                         u32 tmpRegA= rtl8192_QueryBBReg(dev,rOFDM0_XATxIQImbalance,bMaskDWord);
3540                 //      u32 tmpRegC= rtl8192_QueryBBReg(dev,rOFDM0_XCTxIQImbalance,bMaskDWord);
3541                         for(i = 0; i<TxBBGainTableLength; i++)
3542                         {
3543                                 if(tmpRegA == priv->txbbgain_table[i].txbbgain_value)
3544                                 {
3545                                         priv->rfa_txpowertrackingindex= (u8)i;
3546                                         priv->rfa_txpowertrackingindex_real= (u8)i;
3547                                         priv->rfa_txpowertracking_default= priv->rfa_txpowertrackingindex;
3548                                         break;
3549                                 }
3550                         }
3551
3552                         TempCCk = rtl8192_QueryBBReg(dev, rCCK0_TxFilter1, bMaskByte2);
3553
3554                         for(i=0 ; i<CCKTxBBGainTableLength ; i++)
3555                         {
3556
3557                                 if(TempCCk == priv->cck_txbbgain_table[i].ccktxbb_valuearray[0])
3558                                 {
3559                                         priv->cck_present_attentuation_20Mdefault=(u8) i;
3560                                         break;
3561                                 }
3562                         }
3563                         priv->cck_present_attentuation_40Mdefault= 0;
3564                         priv->cck_present_attentuation_difference= 0;
3565                         priv->cck_present_attentuation = priv->cck_present_attentuation_20Mdefault;
3566
3567         //              pMgntInfo->bTXPowerTracking = FALSE;//TEMPLY DISABLE
3568                 }
3569         }
3570         write_nic_byte(dev, 0x87, 0x0);
3571
3572
3573         return init_status;
3574 }
3575
3576 /* this configures registers for beacon tx and enables it via
3577  * rtl8192_beacon_tx_enable(). rtl8192_beacon_tx_disable() might
3578  * be used to stop beacon transmission
3579  */
3580 /***************************************************************************
3581     -------------------------------NET STUFF---------------------------
3582 ***************************************************************************/
3583
3584 static struct net_device_stats *rtl8192_stats(struct net_device *dev)
3585 {
3586         struct r8192_priv *priv = ieee80211_priv(dev);
3587
3588         return &priv->ieee80211->stats;
3589 }
3590
3591 bool
3592 HalTxCheckStuck819xUsb(
3593         struct net_device *dev
3594         )
3595 {
3596         struct r8192_priv *priv = ieee80211_priv(dev);
3597         u16             RegTxCounter = read_nic_word(dev, 0x128);
3598         bool            bStuck = FALSE;
3599         RT_TRACE(COMP_RESET,"%s():RegTxCounter is %d,TxCounter is %d\n",__FUNCTION__,RegTxCounter,priv->TxCounter);
3600         if(priv->TxCounter==RegTxCounter)
3601                 bStuck = TRUE;
3602
3603         priv->TxCounter = RegTxCounter;
3604
3605         return bStuck;
3606 }
3607
3608 /*
3609 *       <Assumption: RT_TX_SPINLOCK is acquired.>
3610 *       First added: 2006.11.19 by emily
3611 */
3612 RESET_TYPE
3613 TxCheckStuck(struct net_device *dev)
3614 {
3615         struct r8192_priv *priv = ieee80211_priv(dev);
3616         u8                      QueueID;
3617 //      PRT_TCB                 pTcb;
3618 //      u8                      ResetThreshold;
3619         bool                    bCheckFwTxCnt = false;
3620         //unsigned long flags;
3621
3622         //
3623         // Decide Stuch threshold according to current power save mode
3624         //
3625
3626 //     RT_TRACE(COMP_RESET, " ==> TxCheckStuck()\n");
3627 //           PlatformAcquireSpinLock(Adapter, RT_TX_SPINLOCK);
3628 //           spin_lock_irqsave(&priv->ieee80211->lock,flags);
3629              for (QueueID = 0; QueueID<=BEACON_QUEUE;QueueID ++)
3630              {
3631                         if(QueueID == TXCMD_QUEUE)
3632                          continue;
3633 #ifdef USB_TX_DRIVER_AGGREGATION_ENABLE
3634                         if((skb_queue_len(&priv->ieee80211->skb_waitQ[QueueID]) == 0) && (skb_queue_len(&priv->ieee80211->skb_aggQ[QueueID]) == 0) && (skb_queue_len(&priv->ieee80211->skb_drv_aggQ[QueueID]) == 0))
3635 #else
3636                         if((skb_queue_len(&priv->ieee80211->skb_waitQ[QueueID]) == 0)  && (skb_queue_len(&priv->ieee80211->skb_aggQ[QueueID]) == 0))
3637 #endif
3638                                 continue;
3639
3640                      bCheckFwTxCnt = true;
3641              }
3642 //           PlatformReleaseSpinLock(Adapter, RT_TX_SPINLOCK);
3643 //      spin_unlock_irqrestore(&priv->ieee80211->lock,flags);
3644 //      RT_TRACE(COMP_RESET,"bCheckFwTxCnt is %d\n",bCheckFwTxCnt);
3645         if(bCheckFwTxCnt)
3646         {
3647                 if(HalTxCheckStuck819xUsb(dev))
3648                 {
3649                         RT_TRACE(COMP_RESET, "TxCheckStuck(): Fw indicates no Tx condition! \n");
3650                         return RESET_TYPE_SILENT;
3651                 }
3652         }
3653         return RESET_TYPE_NORESET;
3654 }
3655
3656 bool
3657 HalRxCheckStuck819xUsb(struct net_device *dev)
3658 {
3659         u16     RegRxCounter = read_nic_word(dev, 0x130);
3660         struct r8192_priv *priv = ieee80211_priv(dev);
3661         bool bStuck = FALSE;
3662         static u8       rx_chk_cnt = 0;
3663         RT_TRACE(COMP_RESET,"%s(): RegRxCounter is %d,RxCounter is %d\n",__FUNCTION__,RegRxCounter,priv->RxCounter);
3664         // If rssi is small, we should check rx for long time because of bad rx.
3665         // or maybe it will continuous silent reset every 2 seconds.
3666         rx_chk_cnt++;
3667         if(priv->undecorated_smoothed_pwdb >= (RateAdaptiveTH_High+5))
3668         {
3669                 rx_chk_cnt = 0; //high rssi, check rx stuck right now.
3670         }
3671         else if(priv->undecorated_smoothed_pwdb < (RateAdaptiveTH_High+5) &&
3672                 ((priv->CurrentChannelBW!=HT_CHANNEL_WIDTH_20&&priv->undecorated_smoothed_pwdb>=RateAdaptiveTH_Low_40M) ||
3673                 (priv->CurrentChannelBW==HT_CHANNEL_WIDTH_20&&priv->undecorated_smoothed_pwdb>=RateAdaptiveTH_Low_20M)) )
3674         {
3675                 if(rx_chk_cnt < 2)
3676                 {
3677                         return bStuck;
3678                 }
3679                 else
3680                 {
3681                         rx_chk_cnt = 0;
3682                 }
3683         }
3684         else if(((priv->CurrentChannelBW!=HT_CHANNEL_WIDTH_20&&priv->undecorated_smoothed_pwdb<RateAdaptiveTH_Low_40M) ||
3685                 (priv->CurrentChannelBW==HT_CHANNEL_WIDTH_20&&priv->undecorated_smoothed_pwdb<RateAdaptiveTH_Low_20M)) &&
3686                 priv->undecorated_smoothed_pwdb >= VeryLowRSSI)
3687         {
3688                 if(rx_chk_cnt < 4)
3689                 {
3690                         //DbgPrint("RSSI < %d && RSSI >= %d, no check this time \n", RateAdaptiveTH_Low, VeryLowRSSI);
3691                         return bStuck;
3692                 }
3693                 else
3694                 {
3695                         rx_chk_cnt = 0;
3696                         //DbgPrint("RSSI < %d && RSSI >= %d, check this time \n", RateAdaptiveTH_Low, VeryLowRSSI);
3697                 }
3698         }
3699         else
3700         {
3701                 if(rx_chk_cnt < 8)
3702                 {
3703                         //DbgPrint("RSSI <= %d, no check this time \n", VeryLowRSSI);
3704                         return bStuck;
3705                 }
3706                 else
3707                 {
3708                         rx_chk_cnt = 0;
3709                         //DbgPrint("RSSI <= %d, check this time \n", VeryLowRSSI);
3710                 }
3711         }
3712
3713         if(priv->RxCounter==RegRxCounter)
3714                 bStuck = TRUE;
3715
3716         priv->RxCounter = RegRxCounter;
3717
3718         return bStuck;
3719 }
3720
3721 RESET_TYPE
3722 RxCheckStuck(struct net_device *dev)
3723 {
3724         struct r8192_priv *priv = ieee80211_priv(dev);
3725         //int                     i;
3726         bool        bRxCheck = FALSE;
3727
3728 //       RT_TRACE(COMP_RESET," ==> RxCheckStuck()\n");
3729         //PlatformAcquireSpinLock(Adapter, RT_RX_SPINLOCK);
3730
3731          if(priv->IrpPendingCount > 1)
3732                 bRxCheck = TRUE;
3733        //PlatformReleaseSpinLock(Adapter, RT_RX_SPINLOCK);
3734
3735 //       RT_TRACE(COMP_RESET,"bRxCheck is %d \n",bRxCheck);
3736         if(bRxCheck)
3737         {
3738                 if(HalRxCheckStuck819xUsb(dev))
3739                 {
3740                         RT_TRACE(COMP_RESET, "RxStuck Condition\n");
3741                         return RESET_TYPE_SILENT;
3742                 }
3743         }
3744         return RESET_TYPE_NORESET;
3745 }
3746
3747
3748 /**
3749 *       This function is called by Checkforhang to check whether we should ask OS to reset driver
3750 *
3751 *       \param pAdapter The adapter context for this miniport
3752 *
3753 *       Note:NIC with USB interface sholud not call this function because we cannot scan descriptor
3754 *       to judge whether there is tx stuck.
3755 *       Note: This function may be required to be rewrite for Vista OS.
3756 *       <<<Assumption: Tx spinlock has been acquired >>>
3757 *
3758 *       8185 and 8185b does not implement this function. This is added by Emily at 2006.11.24
3759 */
3760 RESET_TYPE
3761 rtl819x_ifcheck_resetornot(struct net_device *dev)
3762 {
3763         struct r8192_priv *priv = ieee80211_priv(dev);
3764         RESET_TYPE      TxResetType = RESET_TYPE_NORESET;
3765         RESET_TYPE      RxResetType = RESET_TYPE_NORESET;
3766         RT_RF_POWER_STATE       rfState;
3767
3768         rfState = priv->ieee80211->eRFPowerState;
3769
3770         TxResetType = TxCheckStuck(dev);
3771         if( rfState != eRfOff ||
3772                 /*ADAPTER_TEST_STATUS_FLAG(Adapter, ADAPTER_STATUS_FW_DOWNLOAD_FAILURE)) &&*/
3773                 (priv->ieee80211->iw_mode != IW_MODE_ADHOC))
3774         {
3775                 // If driver is in the status of firmware download failure , driver skips RF initialization and RF is
3776                 // in turned off state. Driver should check whether Rx stuck and do silent reset. And
3777                 // if driver is in firmware download failure status, driver should initialize RF in the following
3778                 // silent reset procedure Emily, 2008.01.21
3779
3780                 // Driver should not check RX stuck in IBSS mode because it is required to
3781                 // set Check BSSID in order to send beacon, however, if check BSSID is
3782                 // set, STA cannot hear any packet a all. Emily, 2008.04.12
3783                 RxResetType = RxCheckStuck(dev);
3784         }
3785         if(TxResetType==RESET_TYPE_NORMAL || RxResetType==RESET_TYPE_NORMAL)
3786                 return RESET_TYPE_NORMAL;
3787         else if(TxResetType==RESET_TYPE_SILENT || RxResetType==RESET_TYPE_SILENT){
3788                 RT_TRACE(COMP_RESET,"%s():silent reset\n",__FUNCTION__);
3789                 return RESET_TYPE_SILENT;
3790         }
3791         else
3792                 return RESET_TYPE_NORESET;
3793
3794 }
3795
3796 void rtl8192_cancel_deferred_work(struct r8192_priv* priv);
3797 int _rtl8192_up(struct net_device *dev);
3798 int rtl8192_close(struct net_device *dev);
3799
3800
3801
3802 void
3803 CamRestoreAllEntry(     struct net_device *dev)
3804 {
3805         u8 EntryId = 0;
3806         struct r8192_priv *priv = ieee80211_priv(dev);
3807         u8*     MacAddr = priv->ieee80211->current_network.bssid;
3808
3809         static u8       CAM_CONST_ADDR[4][6] = {
3810                 {0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
3811                 {0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
3812                 {0x00, 0x00, 0x00, 0x00, 0x00, 0x02},
3813                 {0x00, 0x00, 0x00, 0x00, 0x00, 0x03}};
3814         static u8       CAM_CONST_BROAD[] =
3815                 {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
3816
3817         RT_TRACE(COMP_SEC, "CamRestoreAllEntry: \n");
3818
3819
3820         if ((priv->ieee80211->pairwise_key_type == KEY_TYPE_WEP40)||
3821             (priv->ieee80211->pairwise_key_type == KEY_TYPE_WEP104))
3822         {
3823
3824                 for(EntryId=0; EntryId<4; EntryId++)
3825                 {
3826                         {
3827                                 MacAddr = CAM_CONST_ADDR[EntryId];
3828                                 setKey(dev,
3829                                                 EntryId ,
3830                                                 EntryId,
3831                                                 priv->ieee80211->pairwise_key_type,
3832                                                 MacAddr,
3833                                                 0,
3834                                                 NULL);
3835                         }
3836                 }
3837
3838         }
3839         else if(priv->ieee80211->pairwise_key_type == KEY_TYPE_TKIP)
3840         {
3841
3842                 {
3843                         if(priv->ieee80211->iw_mode == IW_MODE_ADHOC)
3844                                 setKey(dev,
3845                                                 4,
3846                                                 0,
3847                                                 priv->ieee80211->pairwise_key_type,
3848                                                 (u8*)dev->dev_addr,
3849                                                 0,
3850                                                 NULL);
3851                         else
3852                                 setKey(dev,
3853                                                 4,
3854                                                 0,
3855                                                 priv->ieee80211->pairwise_key_type,
3856                                                 MacAddr,
3857                                                 0,
3858                                                 NULL);
3859                 }
3860         }
3861         else if(priv->ieee80211->pairwise_key_type == KEY_TYPE_CCMP)
3862         {
3863
3864                 {
3865                         if(priv->ieee80211->iw_mode == IW_MODE_ADHOC)
3866                                 setKey(dev,
3867                                                 4,
3868                                                 0,
3869                                                 priv->ieee80211->pairwise_key_type,
3870                                                 (u8*)dev->dev_addr,
3871                                                 0,
3872                                                 NULL);
3873                         else
3874                                 setKey(dev,
3875                                                 4,
3876                                                 0,
3877                                                 priv->ieee80211->pairwise_key_type,
3878                                                 MacAddr,
3879                                                 0,
3880                                                 NULL);
3881                 }
3882         }
3883
3884
3885
3886         if(priv->ieee80211->group_key_type == KEY_TYPE_TKIP)
3887         {
3888                 MacAddr = CAM_CONST_BROAD;
3889                 for(EntryId=1 ; EntryId<4 ; EntryId++)
3890                 {
3891                         {
3892                                 setKey(dev,
3893                                                 EntryId,
3894                                                 EntryId,
3895                                                 priv->ieee80211->group_key_type,
3896                                                 MacAddr,
3897                                                 0,
3898                                                 NULL);
3899                         }
3900                 }
3901                 if(priv->ieee80211->iw_mode == IW_MODE_ADHOC)
3902                                 setKey(dev,
3903                                                 0,
3904                                                 0,
3905                                                 priv->ieee80211->group_key_type,
3906                                                 CAM_CONST_ADDR[0],
3907                                                 0,
3908                                                 NULL);
3909         }
3910         else if(priv->ieee80211->group_key_type == KEY_TYPE_CCMP)
3911         {
3912                 MacAddr = CAM_CONST_BROAD;
3913                 for(EntryId=1; EntryId<4 ; EntryId++)
3914                 {
3915                         {
3916                                 setKey(dev,
3917                                                 EntryId ,
3918                                                 EntryId,
3919                                                 priv->ieee80211->group_key_type,
3920                                                 MacAddr,
3921                                                 0,
3922                                                 NULL);
3923                         }
3924                 }
3925
3926                 if(priv->ieee80211->iw_mode == IW_MODE_ADHOC)
3927                                 setKey(dev,
3928                                                 0 ,
3929                                                 0,
3930                                                 priv->ieee80211->group_key_type,
3931                                                 CAM_CONST_ADDR[0],
3932                                                 0,
3933                                                 NULL);
3934         }
3935 }
3936 //////////////////////////////////////////////////////////////
3937 // This function is used to fix Tx/Rx stop bug temporarily.
3938 // This function will do "system reset" to NIC when Tx or Rx is stuck.
3939 // The method checking Tx/Rx stuck of this function is supported by FW,
3940 // which reports Tx and Rx counter to register 0x128 and 0x130.
3941 //////////////////////////////////////////////////////////////
3942 void
3943 rtl819x_ifsilentreset(struct net_device *dev)
3944 {
3945         //OCTET_STRING asocpdu;
3946         struct r8192_priv *priv = ieee80211_priv(dev);
3947         u8      reset_times = 0;
3948         int reset_status = 0;
3949         struct ieee80211_device *ieee = priv->ieee80211;
3950
3951
3952         // 2007.07.20. If we need to check CCK stop, please uncomment this line.
3953         //bStuck = Adapter->HalFunc.CheckHWStopHandler(Adapter);
3954
3955         if(priv->ResetProgress==RESET_TYPE_NORESET)
3956         {
3957 RESET_START:
3958
3959                 RT_TRACE(COMP_RESET,"=========>Reset progress!! \n");
3960
3961                 // Set the variable for reset.
3962                 priv->ResetProgress = RESET_TYPE_SILENT;
3963 //              rtl8192_close(dev);
3964                 down(&priv->wx_sem);
3965                 if(priv->up == 0)
3966                 {
3967                         RT_TRACE(COMP_ERR,"%s():the driver is not up! return\n",__FUNCTION__);
3968                         up(&priv->wx_sem);
3969                         return ;
3970                 }
3971                 priv->up = 0;
3972                 RT_TRACE(COMP_RESET,"%s():======>start to down the driver\n",__FUNCTION__);
3973 //              if(!netif_queue_stopped(dev))
3974 //                      netif_stop_queue(dev);
3975
3976                 rtl8192_rtx_disable(dev);
3977                 rtl8192_cancel_deferred_work(priv);
3978                 deinit_hal_dm(dev);
3979                 del_timer_sync(&priv->watch_dog_timer);
3980
3981                 ieee->sync_scan_hurryup = 1;
3982                 if(ieee->state == IEEE80211_LINKED)
3983                 {
3984                         down(&ieee->wx_sem);
3985                         printk("ieee->state is IEEE80211_LINKED\n");
3986                         ieee80211_stop_send_beacons(priv->ieee80211);
3987                         del_timer_sync(&ieee->associate_timer);
3988                         cancel_delayed_work(&ieee->associate_retry_wq);
3989                         ieee80211_stop_scan(ieee);
3990                         netif_carrier_off(dev);
3991                         up(&ieee->wx_sem);
3992                 }
3993                 else{
3994                         printk("ieee->state is NOT LINKED\n");
3995                         ieee80211_softmac_stop_protocol(priv->ieee80211);                       }
3996                 up(&priv->wx_sem);
3997                 RT_TRACE(COMP_RESET,"%s():<==========down process is finished\n",__FUNCTION__);
3998         //rtl8192_irq_disable(dev);
3999                 RT_TRACE(COMP_RESET,"%s():===========>start to up the driver\n",__FUNCTION__);
4000                 reset_status = _rtl8192_up(dev);
4001
4002                 RT_TRACE(COMP_RESET,"%s():<===========up process is finished\n",__FUNCTION__);
4003                 if(reset_status == -EAGAIN)
4004                 {
4005                         if(reset_times < 3)
4006                         {
4007                                 reset_times++;
4008                                 goto RESET_START;
4009                         }
4010                         else
4011                         {
4012                                 RT_TRACE(COMP_ERR," ERR!!! %s():  Reset Failed!!\n", __FUNCTION__);
4013                         }
4014                 }
4015                 ieee->is_silent_reset = 1;
4016                 EnableHWSecurityConfig8192(dev);
4017                 if(ieee->state == IEEE80211_LINKED && ieee->iw_mode == IW_MODE_INFRA)
4018                 {
4019                         ieee->set_chan(ieee->dev, ieee->current_network.channel);
4020
4021                         queue_work(ieee->wq, &ieee->associate_complete_wq);
4022
4023                 }
4024                 else if(ieee->state == IEEE80211_LINKED && ieee->iw_mode == IW_MODE_ADHOC)
4025                 {
4026                         ieee->set_chan(ieee->dev, ieee->current_network.channel);
4027                         ieee->link_change(ieee->dev);
4028
4029                 //      notify_wx_assoc_event(ieee);
4030
4031                         ieee80211_start_send_beacons(ieee);
4032
4033                         if (ieee->data_hard_resume)
4034                                 ieee->data_hard_resume(ieee->dev);
4035                         netif_carrier_on(ieee->dev);
4036                 }
4037
4038                 CamRestoreAllEntry(dev);
4039
4040                 priv->ResetProgress = RESET_TYPE_NORESET;
4041                 priv->reset_count++;
4042
4043                 priv->bForcedSilentReset =false;
4044                 priv->bResetInProgress = false;
4045
4046                 // For test --> force write UFWP.
4047                 write_nic_byte(dev, UFWP, 1);
4048                 RT_TRACE(COMP_RESET, "Reset finished!! ====>[%d]\n", priv->reset_count);
4049         }
4050 }
4051
4052 void CAM_read_entry(
4053         struct net_device *dev,
4054         u32                     iIndex
4055 )
4056 {
4057         u32 target_command=0;
4058          u32 target_content=0;
4059          u8 entry_i=0;
4060          u32 ulStatus;
4061         s32 i=100;
4062 //      printk("=======>start read CAM\n");
4063         for(entry_i=0;entry_i<CAM_CONTENT_COUNT;entry_i++)
4064         {
4065         // polling bit, and No Write enable, and address
4066                 target_command= entry_i+CAM_CONTENT_COUNT*iIndex;
4067                 target_command= target_command | BIT31;
4068
4069         //Check polling bit is clear
4070 //      mdelay(1);
4071                 while((i--)>=0)
4072                 {
4073                         ulStatus = read_nic_dword(dev, RWCAM);
4074                         if(ulStatus & BIT31){
4075                                 continue;
4076                         }
4077                         else{
4078                                 break;
4079                         }
4080                 }
4081                 write_nic_dword(dev, RWCAM, target_command);
4082                 RT_TRACE(COMP_SEC,"CAM_read_entry(): WRITE A0: %x \n",target_command);
4083          //     printk("CAM_read_entry(): WRITE A0: %lx \n",target_command);
4084                 target_content = read_nic_dword(dev, RCAMO);
4085                 RT_TRACE(COMP_SEC, "CAM_read_entry(): WRITE A8: %x \n",target_content);
4086          //     printk("CAM_read_entry(): WRITE A8: %lx \n",target_content);
4087         }
4088         printk("\n");
4089 }
4090
4091 void rtl819x_update_rxcounts(
4092         struct r8192_priv *priv,
4093         u32* TotalRxBcnNum,
4094         u32* TotalRxDataNum
4095 )
4096 {
4097         u16                     SlotIndex;
4098         u8                      i;
4099
4100         *TotalRxBcnNum = 0;
4101         *TotalRxDataNum = 0;
4102
4103         SlotIndex = (priv->ieee80211->LinkDetectInfo.SlotIndex++)%(priv->ieee80211->LinkDetectInfo.SlotNum);
4104         priv->ieee80211->LinkDetectInfo.RxBcnNum[SlotIndex] = priv->ieee80211->LinkDetectInfo.NumRecvBcnInPeriod;
4105         priv->ieee80211->LinkDetectInfo.RxDataNum[SlotIndex] = priv->ieee80211->LinkDetectInfo.NumRecvDataInPeriod;
4106         for( i=0; i<priv->ieee80211->LinkDetectInfo.SlotNum; i++ ){
4107                 *TotalRxBcnNum += priv->ieee80211->LinkDetectInfo.RxBcnNum[i];
4108                 *TotalRxDataNum += priv->ieee80211->LinkDetectInfo.RxDataNum[i];
4109         }
4110 }
4111
4112
4113 extern  void    rtl819x_watchdog_wqcallback(struct work_struct *work)
4114 {
4115         struct delayed_work *dwork = container_of(work,struct delayed_work,work);
4116        struct r8192_priv *priv = container_of(dwork,struct r8192_priv,watch_dog_wq);
4117        struct net_device *dev = priv->ieee80211->dev;
4118         struct ieee80211_device* ieee = priv->ieee80211;
4119         RESET_TYPE      ResetType = RESET_TYPE_NORESET;
4120         static u8       check_reset_cnt=0;
4121         bool bBusyTraffic = false;
4122
4123         if(!priv->up)
4124                 return;
4125         hal_dm_watchdog(dev);
4126
4127         {//to get busy traffic condition
4128                 if(ieee->state == IEEE80211_LINKED)
4129                 {
4130                         if(     ieee->LinkDetectInfo.NumRxOkInPeriod> 666 ||
4131                                 ieee->LinkDetectInfo.NumTxOkInPeriod> 666 ) {
4132                                 bBusyTraffic = true;
4133                         }
4134                         ieee->LinkDetectInfo.NumRxOkInPeriod = 0;
4135                         ieee->LinkDetectInfo.NumTxOkInPeriod = 0;
4136                         ieee->LinkDetectInfo.bBusyTraffic = bBusyTraffic;
4137                 }
4138         }
4139         //added by amy for AP roaming
4140         {
4141                 if(priv->ieee80211->state == IEEE80211_LINKED && priv->ieee80211->iw_mode == IW_MODE_INFRA)
4142                 {
4143                         u32     TotalRxBcnNum = 0;
4144                         u32     TotalRxDataNum = 0;
4145
4146                         rtl819x_update_rxcounts(priv, &TotalRxBcnNum, &TotalRxDataNum);
4147                         if((TotalRxBcnNum+TotalRxDataNum) == 0)
4148                         {
4149                                 #ifdef TODO
4150                                 if(rfState == eRfOff)
4151                                         RT_TRACE(COMP_ERR,"========>%s()\n",__FUNCTION__);
4152                                 #endif
4153                                 printk("===>%s(): AP is power off,connect another one\n",__FUNCTION__);
4154                         //      Dot11d_Reset(dev);
4155                                 priv->ieee80211->state = IEEE80211_ASSOCIATING;
4156                                 notify_wx_assoc_event(priv->ieee80211);
4157                                 RemovePeerTS(priv->ieee80211,priv->ieee80211->current_network.bssid);
4158                                 priv->ieee80211->link_change(dev);
4159                                 queue_work(priv->ieee80211->wq, &priv->ieee80211->associate_procedure_wq);
4160
4161                         }
4162                 }
4163                 priv->ieee80211->LinkDetectInfo.NumRecvBcnInPeriod=0;
4164                 priv->ieee80211->LinkDetectInfo.NumRecvDataInPeriod=0;
4165         }
4166 //      CAM_read_entry(dev,4);
4167         //check if reset the driver
4168         if(check_reset_cnt++ >= 3)
4169         {
4170                 ResetType = rtl819x_ifcheck_resetornot(dev);
4171                 check_reset_cnt = 3;
4172                 //DbgPrint("Start to check silent reset\n");
4173         }
4174         //      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);
4175         if( (priv->force_reset) || (priv->ResetProgress==RESET_TYPE_NORESET &&
4176                 (priv->bForcedSilentReset ||
4177                 (!priv->bDisableNormalResetCheck && ResetType==RESET_TYPE_SILENT)))) // This is control by OID set in Pomelo
4178         {
4179                 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);
4180                 rtl819x_ifsilentreset(dev);
4181         }
4182         priv->force_reset = false;
4183         priv->bForcedSilentReset = false;
4184         priv->bResetInProgress = false;
4185         RT_TRACE(COMP_TRACE, " <==RtUsbCheckForHangWorkItemCallback()\n");
4186
4187 }
4188
4189 void watch_dog_timer_callback(unsigned long data)
4190 {
4191         struct r8192_priv *priv = ieee80211_priv((struct net_device *) data);
4192         //printk("===============>watch_dog  timer\n");
4193         queue_delayed_work(priv->priv_wq,&priv->watch_dog_wq, 0);
4194         mod_timer(&priv->watch_dog_timer, jiffies + MSECS(IEEE80211_WATCH_DOG_TIME));
4195 }
4196 int _rtl8192_up(struct net_device *dev)
4197 {
4198         struct r8192_priv *priv = ieee80211_priv(dev);
4199         //int i;
4200         int init_status = 0;
4201         priv->up=1;
4202         priv->ieee80211->ieee_up=1;
4203         RT_TRACE(COMP_INIT, "Bringing up iface");
4204         init_status = rtl8192_adapter_start(dev);
4205         if(!init_status)
4206         {
4207                 RT_TRACE(COMP_ERR,"ERR!!! %s(): initialization is failed!\n", __FUNCTION__);
4208                 priv->up=priv->ieee80211->ieee_up = 0;
4209                 return -EAGAIN;
4210         }
4211         RT_TRACE(COMP_INIT, "start adapter finished\n");
4212         rtl8192_rx_enable(dev);
4213 //      rtl8192_tx_enable(dev);
4214         if(priv->ieee80211->state != IEEE80211_LINKED)
4215         ieee80211_softmac_start_protocol(priv->ieee80211);
4216         ieee80211_reset_queue(priv->ieee80211);
4217         watch_dog_timer_callback((unsigned long) dev);
4218         if(!netif_queue_stopped(dev))
4219                 netif_start_queue(dev);
4220         else
4221                 netif_wake_queue(dev);
4222
4223         return 0;
4224 }
4225
4226
4227 int rtl8192_open(struct net_device *dev)
4228 {
4229         struct r8192_priv *priv = ieee80211_priv(dev);
4230         int ret;
4231         down(&priv->wx_sem);
4232         ret = rtl8192_up(dev);
4233         up(&priv->wx_sem);
4234         return ret;
4235
4236 }
4237
4238
4239 int rtl8192_up(struct net_device *dev)
4240 {
4241         struct r8192_priv *priv = ieee80211_priv(dev);
4242
4243         if (priv->up == 1) return -1;
4244
4245         return _rtl8192_up(dev);
4246 }
4247
4248
4249 int rtl8192_close(struct net_device *dev)
4250 {
4251         struct r8192_priv *priv = ieee80211_priv(dev);
4252         int ret;
4253
4254         down(&priv->wx_sem);
4255
4256         ret = rtl8192_down(dev);
4257
4258         up(&priv->wx_sem);
4259
4260         return ret;
4261
4262 }
4263
4264 int rtl8192_down(struct net_device *dev)
4265 {
4266         struct r8192_priv *priv = ieee80211_priv(dev);
4267         int i;
4268
4269         if (priv->up == 0) return -1;
4270
4271         priv->up=0;
4272         priv->ieee80211->ieee_up = 0;
4273         RT_TRACE(COMP_DOWN, "==========>%s()\n", __FUNCTION__);
4274 /* FIXME */
4275         if (!netif_queue_stopped(dev))
4276                 netif_stop_queue(dev);
4277
4278         rtl8192_rtx_disable(dev);
4279         //rtl8192_irq_disable(dev);
4280
4281  /* Tx related queue release */
4282         for(i = 0; i < MAX_QUEUE_SIZE; i++) {
4283                 skb_queue_purge(&priv->ieee80211->skb_waitQ [i]);
4284         }
4285         for(i = 0; i < MAX_QUEUE_SIZE; i++) {
4286                 skb_queue_purge(&priv->ieee80211->skb_aggQ [i]);
4287         }
4288
4289         for(i = 0; i < MAX_QUEUE_SIZE; i++) {
4290                 skb_queue_purge(&priv->ieee80211->skb_drv_aggQ [i]);
4291         }
4292
4293         //as cancel_delayed_work will del work->timer, so if work is not definedas struct delayed_work, it will corrupt
4294 //      flush_scheduled_work();
4295         rtl8192_cancel_deferred_work(priv);
4296         deinit_hal_dm(dev);
4297         del_timer_sync(&priv->watch_dog_timer);
4298
4299
4300         ieee80211_softmac_stop_protocol(priv->ieee80211);
4301         memset(&priv->ieee80211->current_network, 0 , offsetof(struct ieee80211_network, list));
4302         RT_TRACE(COMP_DOWN, "<==========%s()\n", __FUNCTION__);
4303
4304                 return 0;
4305 }
4306
4307
4308 void rtl8192_commit(struct net_device *dev)
4309 {
4310         struct r8192_priv *priv = ieee80211_priv(dev);
4311         int reset_status = 0;
4312         //u8 reset_times = 0;
4313         if (priv->up == 0) return ;
4314         priv->up = 0;
4315
4316         rtl8192_cancel_deferred_work(priv);
4317         del_timer_sync(&priv->watch_dog_timer);
4318         //cancel_delayed_work(&priv->SwChnlWorkItem);
4319
4320         ieee80211_softmac_stop_protocol(priv->ieee80211);
4321
4322         //rtl8192_irq_disable(dev);
4323         rtl8192_rtx_disable(dev);
4324         reset_status = _rtl8192_up(dev);
4325
4326 }
4327
4328 /*
4329 void rtl8192_restart(struct net_device *dev)
4330 {
4331         struct r8192_priv *priv = ieee80211_priv(dev);
4332 */
4333 void rtl8192_restart(struct work_struct *work)
4334 {
4335         struct r8192_priv *priv = container_of(work, struct r8192_priv, reset_wq);
4336         struct net_device *dev = priv->ieee80211->dev;
4337
4338         down(&priv->wx_sem);
4339
4340         rtl8192_commit(dev);
4341
4342         up(&priv->wx_sem);
4343 }
4344
4345 static void r8192_set_multicast(struct net_device *dev)
4346 {
4347         struct r8192_priv *priv = ieee80211_priv(dev);
4348         short promisc;
4349
4350         //down(&priv->wx_sem);
4351
4352         /* FIXME FIXME */
4353
4354         promisc = (dev->flags & IFF_PROMISC) ? 1:0;
4355
4356         if (promisc != priv->promisc)
4357         //      rtl8192_commit(dev);
4358
4359         priv->promisc = promisc;
4360
4361         //schedule_work(&priv->reset_wq);
4362         //up(&priv->wx_sem);
4363 }
4364
4365
4366 int r8192_set_mac_adr(struct net_device *dev, void *mac)
4367 {
4368         struct r8192_priv *priv = ieee80211_priv(dev);
4369         struct sockaddr *addr = mac;
4370
4371         down(&priv->wx_sem);
4372
4373         memcpy(dev->dev_addr, addr->sa_data, ETH_ALEN);
4374
4375         schedule_work(&priv->reset_wq);
4376         up(&priv->wx_sem);
4377
4378         return 0;
4379 }
4380
4381 /* based on ipw2200 driver */
4382 int rtl8192_ioctl(struct net_device *dev, struct ifreq *rq, int cmd)
4383 {
4384         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
4385         struct iwreq *wrq = (struct iwreq *)rq;
4386         int ret=-1;
4387         struct ieee80211_device *ieee = priv->ieee80211;
4388         u32 key[4];
4389         u8 broadcast_addr[6] = {0xff,0xff,0xff,0xff,0xff,0xff};
4390         struct iw_point *p = &wrq->u.data;
4391         struct ieee_param *ipw = NULL;//(struct ieee_param *)wrq->u.data.pointer;
4392
4393         down(&priv->wx_sem);
4394
4395
4396      if (p->length < sizeof(struct ieee_param) || !p->pointer){
4397              ret = -EINVAL;
4398              goto out;
4399         }
4400
4401      ipw = kmalloc(p->length, GFP_KERNEL);
4402      if (ipw == NULL){
4403              ret = -ENOMEM;
4404              goto out;
4405      }
4406      if (copy_from_user(ipw, p->pointer, p->length)) {
4407                 kfree(ipw);
4408             ret = -EFAULT;
4409             goto out;
4410         }
4411
4412         switch (cmd) {
4413             case RTL_IOCTL_WPA_SUPPLICANT:
4414         //parse here for HW security
4415                         if (ipw->cmd == IEEE_CMD_SET_ENCRYPTION)
4416                         {
4417                                 if (ipw->u.crypt.set_tx)
4418                                 {
4419                                         if (strcmp(ipw->u.crypt.alg, "CCMP") == 0)
4420                                                 ieee->pairwise_key_type = KEY_TYPE_CCMP;
4421                                         else if (strcmp(ipw->u.crypt.alg, "TKIP") == 0)
4422                                                 ieee->pairwise_key_type = KEY_TYPE_TKIP;
4423                                         else if (strcmp(ipw->u.crypt.alg, "WEP") == 0)
4424                                         {
4425                                                 if (ipw->u.crypt.key_len == 13)
4426                                                         ieee->pairwise_key_type = KEY_TYPE_WEP104;
4427                                                 else if (ipw->u.crypt.key_len == 5)
4428                                                         ieee->pairwise_key_type = KEY_TYPE_WEP40;
4429                                         }
4430                                         else
4431                                                 ieee->pairwise_key_type = KEY_TYPE_NA;
4432
4433                                         if (ieee->pairwise_key_type)
4434                                         {
4435                                                 memcpy((u8*)key, ipw->u.crypt.key, 16);
4436                                                 EnableHWSecurityConfig8192(dev);
4437                                         //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!
4438                                         //added by WB.
4439                                                 setKey(dev, 4, ipw->u.crypt.idx, ieee->pairwise_key_type, (u8*)ieee->ap_mac_addr, 0, key);
4440                                                 if (ieee->auth_mode != 2)
4441                                                 setKey(dev, ipw->u.crypt.idx, ipw->u.crypt.idx, ieee->pairwise_key_type, (u8*)ieee->ap_mac_addr, 0, key);
4442                                         }
4443                                 }
4444                                 else //if (ipw->u.crypt.idx) //group key use idx > 0
4445                                 {
4446                                         memcpy((u8*)key, ipw->u.crypt.key, 16);
4447                                         if (strcmp(ipw->u.crypt.alg, "CCMP") == 0)
4448                                                 ieee->group_key_type= KEY_TYPE_CCMP;
4449                                         else if (strcmp(ipw->u.crypt.alg, "TKIP") == 0)
4450                                                 ieee->group_key_type = KEY_TYPE_TKIP;
4451                                         else if (strcmp(ipw->u.crypt.alg, "WEP") == 0)
4452                                         {
4453                                                 if (ipw->u.crypt.key_len == 13)
4454                                                         ieee->group_key_type = KEY_TYPE_WEP104;
4455                                                 else if (ipw->u.crypt.key_len == 5)
4456                                                         ieee->group_key_type = KEY_TYPE_WEP40;
4457                                         }
4458                                         else
4459                                                 ieee->group_key_type = KEY_TYPE_NA;
4460
4461                                         if (ieee->group_key_type)
4462                                         {
4463                                                         setKey( dev,
4464                                                                 ipw->u.crypt.idx,
4465                                                                 ipw->u.crypt.idx,               //KeyIndex
4466                                                                 ieee->group_key_type,   //KeyType
4467                                                                 broadcast_addr, //MacAddr
4468                                                                 0,              //DefaultKey
4469                                                                 key);           //KeyContent
4470                                         }
4471                                 }
4472                         }
4473 #ifdef JOHN_HWSEC_DEBUG
4474                 //john's test 0711
4475                 printk("@@ wrq->u pointer = ");
4476                 for(i=0;i<wrq->u.data.length;i++){
4477                         if(i%10==0) printk("\n");
4478                         printk( "%8x|", ((u32*)wrq->u.data.pointer)[i] );
4479                 }
4480                 printk("\n");
4481 #endif /*JOHN_HWSEC_DEBUG*/
4482                 ret = ieee80211_wpa_supplicant_ioctl(priv->ieee80211, &wrq->u.data);
4483                 break;
4484
4485             default:
4486                 ret = -EOPNOTSUPP;
4487                 break;
4488         }
4489         kfree(ipw);
4490         ipw = NULL;
4491 out:
4492         up(&priv->wx_sem);
4493         return ret;
4494 }
4495
4496 u8 HwRateToMRate90(bool bIsHT, u8 rate)
4497 {
4498         u8  ret_rate = 0xff;
4499
4500         if(!bIsHT) {
4501                 switch(rate) {
4502                         case DESC90_RATE1M:   ret_rate = MGN_1M;         break;
4503                         case DESC90_RATE2M:   ret_rate = MGN_2M;         break;
4504                         case DESC90_RATE5_5M: ret_rate = MGN_5_5M;       break;
4505                         case DESC90_RATE11M:  ret_rate = MGN_11M;        break;
4506                         case DESC90_RATE6M:   ret_rate = MGN_6M;         break;
4507                         case DESC90_RATE9M:   ret_rate = MGN_9M;         break;
4508                         case DESC90_RATE12M:  ret_rate = MGN_12M;        break;
4509                         case DESC90_RATE18M:  ret_rate = MGN_18M;        break;
4510                         case DESC90_RATE24M:  ret_rate = MGN_24M;        break;
4511                         case DESC90_RATE36M:  ret_rate = MGN_36M;        break;
4512                         case DESC90_RATE48M:  ret_rate = MGN_48M;        break;
4513                         case DESC90_RATE54M:  ret_rate = MGN_54M;        break;
4514
4515                         default:
4516                                 ret_rate = 0xff;
4517                                 RT_TRACE(COMP_RECV, "HwRateToMRate90(): Non supported Rate [%x], bIsHT = %d!!!\n", rate, bIsHT);
4518                                 break;
4519                 }
4520
4521         } else {
4522                 switch(rate) {
4523                         case DESC90_RATEMCS0:   ret_rate = MGN_MCS0;    break;
4524                         case DESC90_RATEMCS1:   ret_rate = MGN_MCS1;    break;
4525                         case DESC90_RATEMCS2:   ret_rate = MGN_MCS2;    break;
4526                         case DESC90_RATEMCS3:   ret_rate = MGN_MCS3;    break;
4527                         case DESC90_RATEMCS4:   ret_rate = MGN_MCS4;    break;
4528                         case DESC90_RATEMCS5:   ret_rate = MGN_MCS5;    break;
4529                         case DESC90_RATEMCS6:   ret_rate = MGN_MCS6;    break;
4530                         case DESC90_RATEMCS7:   ret_rate = MGN_MCS7;    break;
4531                         case DESC90_RATEMCS8:   ret_rate = MGN_MCS8;    break;
4532                         case DESC90_RATEMCS9:   ret_rate = MGN_MCS9;    break;
4533                         case DESC90_RATEMCS10:  ret_rate = MGN_MCS10;   break;
4534                         case DESC90_RATEMCS11:  ret_rate = MGN_MCS11;   break;
4535                         case DESC90_RATEMCS12:  ret_rate = MGN_MCS12;   break;
4536                         case DESC90_RATEMCS13:  ret_rate = MGN_MCS13;   break;
4537                         case DESC90_RATEMCS14:  ret_rate = MGN_MCS14;   break;
4538                         case DESC90_RATEMCS15:  ret_rate = MGN_MCS15;   break;
4539                         case DESC90_RATEMCS32:  ret_rate = (0x80|0x20); break;
4540
4541                         default:
4542                                 ret_rate = 0xff;
4543                                 RT_TRACE(COMP_RECV, "HwRateToMRate90(): Non supported Rate [%x], bIsHT = %d!!!\n",rate, bIsHT);
4544                                 break;
4545                 }
4546         }
4547
4548         return ret_rate;
4549 }
4550
4551 /**
4552  * Function:     UpdateRxPktTimeStamp
4553  * Overview:     Recored down the TSF time stamp when receiving a packet
4554  *
4555  * Input:
4556  *       PADAPTER        Adapter
4557  *       PRT_RFD         pRfd,
4558  *
4559  * Output:
4560  *       PRT_RFD         pRfd
4561  *                               (pRfd->Status.TimeStampHigh is updated)
4562  *                               (pRfd->Status.TimeStampLow is updated)
4563  * Return:
4564  *               None
4565  */
4566 void UpdateRxPktTimeStamp8190 (struct net_device *dev, struct ieee80211_rx_stats *stats)
4567 {
4568         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
4569
4570         if(stats->bIsAMPDU && !stats->bFirstMPDU) {
4571                 stats->mac_time[0] = priv->LastRxDescTSFLow;
4572                 stats->mac_time[1] = priv->LastRxDescTSFHigh;
4573         } else {
4574                 priv->LastRxDescTSFLow = stats->mac_time[0];
4575                 priv->LastRxDescTSFHigh = stats->mac_time[1];
4576         }
4577 }
4578
4579 //by amy 080606
4580
4581 long rtl819x_translate_todbm(u8 signal_strength_index   )// 0-100 index.
4582 {
4583         long    signal_power; // in dBm.
4584
4585         // Translate to dBm (x=0.5y-95).
4586         signal_power = (long)((signal_strength_index + 1) >> 1);
4587         signal_power -= 95;
4588
4589         return signal_power;
4590 }
4591
4592
4593 /* 2008/01/22 MH We can not delcare RSSI/EVM total value of sliding window to
4594     be a local static. Otherwise, it may increase when we return from S3/S4. The
4595     value will be kept in memory or disk. We must delcare the value in adapter
4596     and it will be reinitialized when return from S3/S4. */
4597 void rtl8192_process_phyinfo(struct r8192_priv * priv,u8* buffer, struct ieee80211_rx_stats * pprevious_stats, struct ieee80211_rx_stats * pcurrent_stats)
4598 {
4599         bool bcheck = false;
4600         u8      rfpath;
4601         u32     nspatial_stream, tmp_val;
4602         //u8    i;
4603         static u32 slide_rssi_index=0, slide_rssi_statistics=0;
4604         static u32 slide_evm_index=0, slide_evm_statistics=0;
4605         static u32 last_rssi=0, last_evm=0;
4606
4607         static u32 slide_beacon_adc_pwdb_index=0, slide_beacon_adc_pwdb_statistics=0;
4608         static u32 last_beacon_adc_pwdb=0;
4609
4610         struct ieee80211_hdr_3addr *hdr;
4611         u16 sc ;
4612         unsigned int frag,seq;
4613         hdr = (struct ieee80211_hdr_3addr *)buffer;
4614         sc = le16_to_cpu(hdr->seq_ctl);
4615         frag = WLAN_GET_SEQ_FRAG(sc);
4616         seq = WLAN_GET_SEQ_SEQ(sc);
4617         //cosa add 04292008 to record the sequence number
4618         pcurrent_stats->Seq_Num = seq;
4619         //
4620         // Check whether we should take the previous packet into accounting
4621         //
4622         if(!pprevious_stats->bIsAMPDU)
4623         {
4624                 // if previous packet is not aggregated packet
4625                 bcheck = true;
4626         }else
4627         {
4628         }
4629
4630
4631         if(slide_rssi_statistics++ >= PHY_RSSI_SLID_WIN_MAX)
4632         {
4633                 slide_rssi_statistics = PHY_RSSI_SLID_WIN_MAX;
4634                 last_rssi = priv->stats.slide_signal_strength[slide_rssi_index];
4635                 priv->stats.slide_rssi_total -= last_rssi;
4636         }
4637         priv->stats.slide_rssi_total += pprevious_stats->SignalStrength;
4638
4639         priv->stats.slide_signal_strength[slide_rssi_index++] = pprevious_stats->SignalStrength;
4640         if(slide_rssi_index >= PHY_RSSI_SLID_WIN_MAX)
4641                 slide_rssi_index = 0;
4642
4643         // <1> Showed on UI for user, in dbm
4644         tmp_val = priv->stats.slide_rssi_total/slide_rssi_statistics;
4645         priv->stats.signal_strength = rtl819x_translate_todbm((u8)tmp_val);
4646         pcurrent_stats->rssi = priv->stats.signal_strength;
4647         //
4648         // If the previous packet does not match the criteria, neglect it
4649         //
4650         if(!pprevious_stats->bPacketMatchBSSID)
4651         {
4652                 if(!pprevious_stats->bToSelfBA)
4653                         return;
4654         }
4655
4656         if(!bcheck)
4657                 return;
4658
4659
4660         //rtl8190_process_cck_rxpathsel(priv,pprevious_stats);//only rtl8190 supported
4661
4662         //
4663         // Check RSSI
4664         //
4665         priv->stats.num_process_phyinfo++;
4666
4667         /* record the general signal strength to the sliding window. */
4668
4669
4670         // <2> Showed on UI for engineering
4671         // hardware does not provide rssi information for each rf path in CCK
4672         if(!pprevious_stats->bIsCCK && (pprevious_stats->bPacketToSelf || pprevious_stats->bToSelfBA))
4673         {
4674                 for (rfpath = RF90_PATH_A; rfpath < priv->NumTotalRFPath; rfpath++)
4675                 {
4676                      if (!rtl8192_phy_CheckIsLegalRFPath(priv->ieee80211->dev, rfpath))
4677                                  continue;
4678
4679                         //Fixed by Jacken 2008-03-20
4680                         if(priv->stats.rx_rssi_percentage[rfpath] == 0)
4681                         {
4682                                 priv->stats.rx_rssi_percentage[rfpath] = pprevious_stats->RxMIMOSignalStrength[rfpath];
4683                                 //DbgPrint("MIMO RSSI initialize \n");
4684                         }
4685                         if(pprevious_stats->RxMIMOSignalStrength[rfpath]  > priv->stats.rx_rssi_percentage[rfpath])
4686                         {
4687                                 priv->stats.rx_rssi_percentage[rfpath] =
4688                                         ( (priv->stats.rx_rssi_percentage[rfpath]*(Rx_Smooth_Factor-1)) +
4689                                         (pprevious_stats->RxMIMOSignalStrength[rfpath])) /(Rx_Smooth_Factor);
4690                                 priv->stats.rx_rssi_percentage[rfpath] = priv->stats.rx_rssi_percentage[rfpath]  + 1;
4691                         }
4692                         else
4693                         {
4694                                 priv->stats.rx_rssi_percentage[rfpath] =
4695                                         ( (priv->stats.rx_rssi_percentage[rfpath]*(Rx_Smooth_Factor-1)) +
4696                                         (pprevious_stats->RxMIMOSignalStrength[rfpath])) /(Rx_Smooth_Factor);
4697                         }
4698                         RT_TRACE(COMP_DBG,"priv->stats.rx_rssi_percentage[rfPath]  = %d \n" ,priv->stats.rx_rssi_percentage[rfpath] );
4699                 }
4700         }
4701
4702
4703         //
4704         // Check PWDB.
4705         //
4706         RT_TRACE(COMP_RXDESC, "Smooth %s PWDB = %d\n",
4707                                 pprevious_stats->bIsCCK? "CCK": "OFDM",
4708                                 pprevious_stats->RxPWDBAll);
4709
4710         if(pprevious_stats->bPacketBeacon)
4711         {
4712 /* record the beacon pwdb to the sliding window. */
4713                 if(slide_beacon_adc_pwdb_statistics++ >= PHY_Beacon_RSSI_SLID_WIN_MAX)
4714                 {
4715                         slide_beacon_adc_pwdb_statistics = PHY_Beacon_RSSI_SLID_WIN_MAX;
4716                         last_beacon_adc_pwdb = priv->stats.Slide_Beacon_pwdb[slide_beacon_adc_pwdb_index];
4717                         priv->stats.Slide_Beacon_Total -= last_beacon_adc_pwdb;
4718                         //DbgPrint("slide_beacon_adc_pwdb_index = %d, last_beacon_adc_pwdb = %d, Adapter->RxStats.Slide_Beacon_Total = %d\n",
4719                         //      slide_beacon_adc_pwdb_index, last_beacon_adc_pwdb, Adapter->RxStats.Slide_Beacon_Total);
4720                 }
4721                 priv->stats.Slide_Beacon_Total += pprevious_stats->RxPWDBAll;
4722                 priv->stats.Slide_Beacon_pwdb[slide_beacon_adc_pwdb_index] = pprevious_stats->RxPWDBAll;
4723                 //DbgPrint("slide_beacon_adc_pwdb_index = %d, pPreviousRfd->Status.RxPWDBAll = %d\n", slide_beacon_adc_pwdb_index, pPreviousRfd->Status.RxPWDBAll);
4724                 slide_beacon_adc_pwdb_index++;
4725                 if(slide_beacon_adc_pwdb_index >= PHY_Beacon_RSSI_SLID_WIN_MAX)
4726                         slide_beacon_adc_pwdb_index = 0;
4727                 pprevious_stats->RxPWDBAll = priv->stats.Slide_Beacon_Total/slide_beacon_adc_pwdb_statistics;
4728                 if(pprevious_stats->RxPWDBAll >= 3)
4729                         pprevious_stats->RxPWDBAll -= 3;
4730         }
4731
4732         RT_TRACE(COMP_RXDESC, "Smooth %s PWDB = %d\n",
4733                                 pprevious_stats->bIsCCK? "CCK": "OFDM",
4734                                 pprevious_stats->RxPWDBAll);
4735
4736
4737         if(pprevious_stats->bPacketToSelf || pprevious_stats->bPacketBeacon || pprevious_stats->bToSelfBA)
4738         {
4739                 if(priv->undecorated_smoothed_pwdb < 0) // initialize
4740                 {
4741                         priv->undecorated_smoothed_pwdb = pprevious_stats->RxPWDBAll;
4742                         //DbgPrint("First pwdb initialize \n");
4743                 }
4744                 if(pprevious_stats->RxPWDBAll > (u32)priv->undecorated_smoothed_pwdb)
4745                 {
4746                         priv->undecorated_smoothed_pwdb =
4747                                         ( ((priv->undecorated_smoothed_pwdb)*(Rx_Smooth_Factor-1)) +
4748                                         (pprevious_stats->RxPWDBAll)) /(Rx_Smooth_Factor);
4749                         priv->undecorated_smoothed_pwdb = priv->undecorated_smoothed_pwdb + 1;
4750                 }
4751                 else
4752                 {
4753                         priv->undecorated_smoothed_pwdb =
4754                                         ( ((priv->undecorated_smoothed_pwdb)*(Rx_Smooth_Factor-1)) +
4755                                         (pprevious_stats->RxPWDBAll)) /(Rx_Smooth_Factor);
4756                 }
4757
4758         }
4759
4760         //
4761         // Check EVM
4762         //
4763         /* record the general EVM to the sliding window. */
4764         if(pprevious_stats->SignalQuality == 0)
4765         {
4766         }
4767         else
4768         {
4769                 if(pprevious_stats->bPacketToSelf || pprevious_stats->bPacketBeacon || pprevious_stats->bToSelfBA){
4770                         if(slide_evm_statistics++ >= PHY_RSSI_SLID_WIN_MAX){
4771                                 slide_evm_statistics = PHY_RSSI_SLID_WIN_MAX;
4772                                 last_evm = priv->stats.slide_evm[slide_evm_index];
4773                                 priv->stats.slide_evm_total -= last_evm;
4774                         }
4775
4776                         priv->stats.slide_evm_total += pprevious_stats->SignalQuality;
4777
4778                         priv->stats.slide_evm[slide_evm_index++] = pprevious_stats->SignalQuality;
4779                         if(slide_evm_index >= PHY_RSSI_SLID_WIN_MAX)
4780                                 slide_evm_index = 0;
4781
4782                         // <1> Showed on UI for user, in percentage.
4783                         tmp_val = priv->stats.slide_evm_total/slide_evm_statistics;
4784                         priv->stats.signal_quality = tmp_val;
4785                         //cosa add 10/11/2007, Showed on UI for user in Windows Vista, for Link quality.
4786                         priv->stats.last_signal_strength_inpercent = tmp_val;
4787                 }
4788
4789                 // <2> Showed on UI for engineering
4790                 if(pprevious_stats->bPacketToSelf || pprevious_stats->bPacketBeacon || pprevious_stats->bToSelfBA)
4791                 {
4792                         for(nspatial_stream = 0; nspatial_stream<2 ; nspatial_stream++) // 2 spatial stream
4793                         {
4794                                 if(pprevious_stats->RxMIMOSignalQuality[nspatial_stream] != -1)
4795                                 {
4796                                         if(priv->stats.rx_evm_percentage[nspatial_stream] == 0) // initialize
4797                                         {
4798                                                 priv->stats.rx_evm_percentage[nspatial_stream] = pprevious_stats->RxMIMOSignalQuality[nspatial_stream];
4799                                         }
4800                                         priv->stats.rx_evm_percentage[nspatial_stream] =
4801                                                 ( (priv->stats.rx_evm_percentage[nspatial_stream]* (Rx_Smooth_Factor-1)) +
4802                                                 (pprevious_stats->RxMIMOSignalQuality[nspatial_stream]* 1)) / (Rx_Smooth_Factor);
4803                                 }
4804                         }
4805                 }
4806         }
4807
4808
4809 }
4810
4811 /*-----------------------------------------------------------------------------
4812  * Function:    rtl819x_query_rxpwrpercentage()
4813  *
4814  * Overview:
4815  *
4816  * Input:               char            antpower
4817  *
4818  * Output:              NONE
4819  *
4820  * Return:              0-100 percentage
4821  *
4822  * Revised History:
4823  *      When            Who             Remark
4824  *      05/26/2008      amy             Create Version 0 porting from windows code.
4825  *
4826  *---------------------------------------------------------------------------*/
4827 static u8 rtl819x_query_rxpwrpercentage(
4828         char            antpower
4829         )
4830 {
4831         if ((antpower <= -100) || (antpower >= 20))
4832         {
4833                 return  0;
4834         }
4835         else if (antpower >= 0)
4836         {
4837                 return  100;
4838         }
4839         else
4840         {
4841                 return  (100+antpower);
4842         }
4843
4844 }       /* QueryRxPwrPercentage */
4845
4846 static u8
4847 rtl819x_evm_dbtopercentage(
4848     char value
4849     )
4850 {
4851     char ret_val;
4852
4853     ret_val = value;
4854
4855     if(ret_val >= 0)
4856         ret_val = 0;
4857     if(ret_val <= -33)
4858         ret_val = -33;
4859     ret_val = 0 - ret_val;
4860     ret_val*=3;
4861         if(ret_val == 99)
4862                 ret_val = 100;
4863     return(ret_val);
4864 }
4865 //
4866 //      Description:
4867 //      We want good-looking for signal strength/quality
4868 //      2007/7/19 01:09, by cosa.
4869 //
4870 long
4871 rtl819x_signal_scale_mapping(
4872         long currsig
4873         )
4874 {
4875         long retsig;
4876
4877         // Step 1. Scale mapping.
4878         if(currsig >= 61 && currsig <= 100)
4879         {
4880                 retsig = 90 + ((currsig - 60) / 4);
4881         }
4882         else if(currsig >= 41 && currsig <= 60)
4883         {
4884                 retsig = 78 + ((currsig - 40) / 2);
4885         }
4886         else if(currsig >= 31 && currsig <= 40)
4887         {
4888                 retsig = 66 + (currsig - 30);
4889         }
4890         else if(currsig >= 21 && currsig <= 30)
4891         {
4892                 retsig = 54 + (currsig - 20);
4893         }
4894         else if(currsig >= 5 && currsig <= 20)
4895         {
4896                 retsig = 42 + (((currsig - 5) * 2) / 3);
4897         }
4898         else if(currsig == 4)
4899         {
4900                 retsig = 36;
4901         }
4902         else if(currsig == 3)
4903         {
4904                 retsig = 27;
4905         }
4906         else if(currsig == 2)
4907         {
4908                 retsig = 18;
4909         }
4910         else if(currsig == 1)
4911         {
4912                 retsig = 9;
4913         }
4914         else
4915         {
4916                 retsig = currsig;
4917         }
4918
4919         return retsig;
4920 }
4921
4922 static void rtl8192_query_rxphystatus(
4923         struct r8192_priv * priv,
4924         struct ieee80211_rx_stats * pstats,
4925         rx_drvinfo_819x_usb  * pdrvinfo,
4926         struct ieee80211_rx_stats * precord_stats,
4927         bool bpacket_match_bssid,
4928         bool bpacket_toself,
4929         bool bPacketBeacon,
4930         bool bToSelfBA
4931         )
4932 {
4933         //PRT_RFD_STATUS                pRtRfdStatus = &(pRfd->Status);
4934         phy_sts_ofdm_819xusb_t* pofdm_buf;
4935         phy_sts_cck_819xusb_t   *       pcck_buf;
4936         phy_ofdm_rx_status_rxsc_sgien_exintfflag* prxsc;
4937         u8                              *prxpkt;
4938         u8                              i, max_spatial_stream, tmp_rxsnr, tmp_rxevm, rxsc_sgien_exflg;
4939         char                            rx_pwr[4], rx_pwr_all=0;
4940         //long                          rx_avg_pwr = 0;
4941         char                            rx_snrX, rx_evmX;
4942         u8                              evm, pwdb_all;
4943         u32                             RSSI, total_rssi=0;//, total_evm=0;
4944 //      long                            signal_strength_index = 0;
4945         u8                              is_cck_rate=0;
4946         u8                              rf_rx_num = 0;
4947
4948
4949         priv->stats.numqry_phystatus++;
4950
4951         is_cck_rate = rx_hal_is_cck_rate(pdrvinfo);
4952
4953         // Record it for next packet processing
4954         memset(precord_stats, 0, sizeof(struct ieee80211_rx_stats));
4955         pstats->bPacketMatchBSSID = precord_stats->bPacketMatchBSSID = bpacket_match_bssid;
4956         pstats->bPacketToSelf = precord_stats->bPacketToSelf = bpacket_toself;
4957         pstats->bIsCCK = precord_stats->bIsCCK = is_cck_rate;//RX_HAL_IS_CCK_RATE(pDrvInfo);
4958         pstats->bPacketBeacon = precord_stats->bPacketBeacon = bPacketBeacon;
4959         pstats->bToSelfBA = precord_stats->bToSelfBA = bToSelfBA;
4960
4961         prxpkt = (u8*)pdrvinfo;
4962
4963         /* Move pointer to the 16th bytes. Phy status start address. */
4964         prxpkt += sizeof(rx_drvinfo_819x_usb);
4965
4966         /* Initial the cck and ofdm buffer pointer */
4967         pcck_buf = (phy_sts_cck_819xusb_t *)prxpkt;
4968         pofdm_buf = (phy_sts_ofdm_819xusb_t *)prxpkt;
4969
4970         pstats->RxMIMOSignalQuality[0] = -1;
4971         pstats->RxMIMOSignalQuality[1] = -1;
4972         precord_stats->RxMIMOSignalQuality[0] = -1;
4973         precord_stats->RxMIMOSignalQuality[1] = -1;
4974
4975         if(is_cck_rate)
4976         {
4977                 //
4978                 // (1)Hardware does not provide RSSI for CCK
4979                 //
4980
4981                 //
4982                 // (2)PWDB, Average PWDB cacluated by hardware (for rate adaptive)
4983                 //
4984                 u8 report;//, cck_agc_rpt;
4985
4986                 priv->stats.numqry_phystatusCCK++;
4987
4988                 if(!priv->bCckHighPower)
4989                 {
4990                         report = pcck_buf->cck_agc_rpt & 0xc0;
4991                         report = report>>6;
4992                         switch(report)
4993                         {
4994                                 //Fixed by Jacken from Bryant 2008-03-20
4995                                 //Original value is -38 , -26 , -14 , -2
4996                                 //Fixed value is -35 , -23 , -11 , 6
4997                                 case 0x3:
4998                                         rx_pwr_all = -35 - (pcck_buf->cck_agc_rpt & 0x3e);
4999                                         break;
5000                                 case 0x2:
5001                                         rx_pwr_all = -23 - (pcck_buf->cck_agc_rpt & 0x3e);
5002                                         break;
5003                                 case 0x1:
5004                                         rx_pwr_all = -11 - (pcck_buf->cck_agc_rpt & 0x3e);
5005                                         break;
5006                                 case 0x0:
5007                                         rx_pwr_all = 6 - (pcck_buf->cck_agc_rpt & 0x3e);
5008                                         break;
5009                         }
5010                 }
5011                 else
5012                 {
5013                         report = pcck_buf->cck_agc_rpt & 0x60;
5014                         report = report>>5;
5015                         switch(report)
5016                         {
5017                                 case 0x3:
5018                                         rx_pwr_all = -35 - ((pcck_buf->cck_agc_rpt & 0x1f)<<1) ;
5019                                         break;
5020                                 case 0x2:
5021                                         rx_pwr_all = -23 - ((pcck_buf->cck_agc_rpt & 0x1f)<<1);
5022                                         break;
5023                                 case 0x1:
5024                                         rx_pwr_all = -11 - ((pcck_buf->cck_agc_rpt & 0x1f)<<1) ;
5025                                         break;
5026                                 case 0x0:
5027                                         rx_pwr_all = 6 - ((pcck_buf->cck_agc_rpt & 0x1f)<<1) ;
5028                                         break;
5029                         }
5030                 }
5031
5032                 pwdb_all = rtl819x_query_rxpwrpercentage(rx_pwr_all);
5033                 pstats->RxPWDBAll = precord_stats->RxPWDBAll = pwdb_all;
5034                 pstats->RecvSignalPower = pwdb_all;
5035
5036                 //
5037                 // (3) Get Signal Quality (EVM)
5038                 //
5039                 //if(bpacket_match_bssid)
5040                 {
5041                         u8      sq;
5042
5043                         if(pstats->RxPWDBAll > 40)
5044                         {
5045                                 sq = 100;
5046                         }else
5047                         {
5048                                 sq = pcck_buf->sq_rpt;
5049
5050                                 if(pcck_buf->sq_rpt > 64)
5051                                         sq = 0;
5052                                 else if (pcck_buf->sq_rpt < 20)
5053                                         sq = 100;
5054                                 else
5055                                         sq = ((64-sq) * 100) / 44;
5056                         }
5057                         pstats->SignalQuality = precord_stats->SignalQuality = sq;
5058                         pstats->RxMIMOSignalQuality[0] = precord_stats->RxMIMOSignalQuality[0] = sq;
5059                         pstats->RxMIMOSignalQuality[1] = precord_stats->RxMIMOSignalQuality[1] = -1;
5060                 }
5061         }
5062         else
5063         {
5064                 priv->stats.numqry_phystatusHT++;
5065                 //
5066                 // (1)Get RSSI for HT rate
5067                 //
5068                 for(i=RF90_PATH_A; i<priv->NumTotalRFPath; i++)
5069                 {
5070                         // 2008/01/30 MH we will judge RF RX path now.
5071                         if (priv->brfpath_rxenable[i])
5072                                 rf_rx_num++;
5073                         else
5074                                 continue;
5075
5076                 if (!rtl8192_phy_CheckIsLegalRFPath(priv->ieee80211->dev, i))
5077                                 continue;
5078
5079                         //Fixed by Jacken from Bryant 2008-03-20
5080                         //Original value is 106
5081                         rx_pwr[i] = ((pofdm_buf->trsw_gain_X[i]&0x3F)*2) - 106;
5082
5083                         //Get Rx snr value in DB
5084                         tmp_rxsnr =     pofdm_buf->rxsnr_X[i];
5085                         rx_snrX = (char)(tmp_rxsnr);
5086                         //rx_snrX >>= 1;;
5087                         rx_snrX /= 2;
5088                         priv->stats.rxSNRdB[i] = (long)rx_snrX;
5089
5090                         /* Translate DBM to percentage. */
5091                         RSSI = rtl819x_query_rxpwrpercentage(rx_pwr[i]);
5092                         total_rssi += RSSI;
5093
5094                         /* Record Signal Strength for next packet */
5095                         //if(bpacket_match_bssid)
5096                         {
5097                                 pstats->RxMIMOSignalStrength[i] =(u8) RSSI;
5098                                 precord_stats->RxMIMOSignalStrength[i] =(u8) RSSI;
5099                         }
5100                 }
5101
5102
5103                 //
5104                 // (2)PWDB, Average PWDB cacluated by hardware (for rate adaptive)
5105                 //
5106                 //Fixed by Jacken from Bryant 2008-03-20
5107                 //Original value is 106
5108                 rx_pwr_all = (((pofdm_buf->pwdb_all ) >> 1 )& 0x7f) -106;
5109                 pwdb_all = rtl819x_query_rxpwrpercentage(rx_pwr_all);
5110
5111                 pstats->RxPWDBAll = precord_stats->RxPWDBAll = pwdb_all;
5112                 pstats->RxPower = precord_stats->RxPower =  rx_pwr_all;
5113
5114                 //
5115                 // (3)EVM of HT rate
5116                 //
5117                 if(pdrvinfo->RxHT && pdrvinfo->RxRate>=DESC90_RATEMCS8 &&
5118                         pdrvinfo->RxRate<=DESC90_RATEMCS15)
5119                         max_spatial_stream = 2; //both spatial stream make sense
5120                 else
5121                         max_spatial_stream = 1; //only spatial stream 1 makes sense
5122
5123                 for(i=0; i<max_spatial_stream; i++)
5124                 {
5125                         tmp_rxevm =     pofdm_buf->rxevm_X[i];
5126                         rx_evmX = (char)(tmp_rxevm);
5127
5128                         // Do not use shift operation like "rx_evmX >>= 1" because the compilor of free build environment
5129                         // fill most significant bit to "zero" when doing shifting operation which may change a negative
5130                         // value to positive one, then the dbm value (which is supposed to be negative)  is not correct anymore.
5131                         rx_evmX /= 2;   //dbm
5132
5133                         evm = rtl819x_evm_dbtopercentage(rx_evmX);
5134                         //if(bpacket_match_bssid)
5135                         {
5136                                 if(i==0) // Fill value in RFD, Get the first spatial stream only
5137                                         pstats->SignalQuality = precord_stats->SignalQuality = (u8)(evm & 0xff);
5138                                 pstats->RxMIMOSignalQuality[i] = precord_stats->RxMIMOSignalQuality[i] = (u8)(evm & 0xff);
5139                         }
5140                 }
5141
5142
5143                 /* record rx statistics for debug */
5144                 rxsc_sgien_exflg = pofdm_buf->rxsc_sgien_exflg;
5145                 prxsc = (phy_ofdm_rx_status_rxsc_sgien_exintfflag *)&rxsc_sgien_exflg;
5146                 if(pdrvinfo->BW)        //40M channel
5147                         priv->stats.received_bwtype[1+prxsc->rxsc]++;
5148                 else                            //20M channel
5149                         priv->stats.received_bwtype[0]++;
5150         }
5151
5152         //UI BSS List signal strength(in percentage), make it good looking, from 0~100.
5153         //It is assigned to the BSS List in GetValueFromBeaconOrProbeRsp().
5154         if(is_cck_rate)
5155         {
5156                 pstats->SignalStrength = precord_stats->SignalStrength = (u8)(rtl819x_signal_scale_mapping((long)pwdb_all));//PWDB_ALL;
5157
5158         }
5159         else
5160         {
5161                 //pRfd->Status.SignalStrength = pRecordRfd->Status.SignalStrength = (u8)(SignalScaleMapping(total_rssi/=RF90_PATH_MAX));//(u8)(total_rssi/=RF90_PATH_MAX);
5162                 // We can judge RX path number now.
5163                 if (rf_rx_num != 0)
5164                         pstats->SignalStrength = precord_stats->SignalStrength = (u8)(rtl819x_signal_scale_mapping((long)(total_rssi/=rf_rx_num)));
5165         }
5166 }       /* QueryRxPhyStatus8190Pci */
5167
5168 void
5169 rtl8192_record_rxdesc_forlateruse(
5170         struct ieee80211_rx_stats *     psrc_stats,
5171         struct ieee80211_rx_stats *     ptarget_stats
5172 )
5173 {
5174         ptarget_stats->bIsAMPDU = psrc_stats->bIsAMPDU;
5175         ptarget_stats->bFirstMPDU = psrc_stats->bFirstMPDU;
5176         ptarget_stats->Seq_Num = psrc_stats->Seq_Num;
5177 }
5178
5179
5180 void TranslateRxSignalStuff819xUsb(struct sk_buff *skb,
5181                                    struct ieee80211_rx_stats * pstats,
5182                                    rx_drvinfo_819x_usb  *pdrvinfo)
5183 {
5184         // TODO: We must only check packet for current MAC address. Not finish
5185         rtl8192_rx_info *info = (struct rtl8192_rx_info *)skb->cb;
5186         struct net_device *dev=info->dev;
5187         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
5188         bool bpacket_match_bssid, bpacket_toself;
5189         bool bPacketBeacon=FALSE, bToSelfBA=FALSE;
5190         static struct ieee80211_rx_stats  previous_stats;
5191         struct ieee80211_hdr_3addr *hdr;//by amy
5192        u16 fc,type;
5193
5194         // Get Signal Quality for only RX data queue (but not command queue)
5195
5196         u8* tmp_buf;
5197         //u16 tmp_buf_len = 0;
5198         u8  *praddr;
5199
5200         /* Get MAC frame start address. */
5201         tmp_buf = (u8*)skb->data;// + get_rxpacket_shiftbytes_819xusb(pstats);
5202
5203         hdr = (struct ieee80211_hdr_3addr *)tmp_buf;
5204         fc = le16_to_cpu(hdr->frame_ctl);
5205         type = WLAN_FC_GET_TYPE(fc);
5206         praddr = hdr->addr1;
5207
5208         /* Check if the received packet is acceptabe. */
5209         bpacket_match_bssid = ((IEEE80211_FTYPE_CTL != type) &&
5210                                                         (eqMacAddr(priv->ieee80211->current_network.bssid,  (fc & IEEE80211_FCTL_TODS)? hdr->addr1 : (fc & IEEE80211_FCTL_FROMDS )? hdr->addr2 : hdr->addr3))
5211                                                                  && (!pstats->bHwError) && (!pstats->bCRC)&& (!pstats->bICV));
5212         bpacket_toself =  bpacket_match_bssid & (eqMacAddr(praddr, priv->ieee80211->dev->dev_addr));
5213
5214                 if(WLAN_FC_GET_FRAMETYPE(fc)== IEEE80211_STYPE_BEACON)
5215                 {
5216                         bPacketBeacon = true;
5217                         //DbgPrint("Beacon 2, MatchBSSID = %d, ToSelf = %d \n", bPacketMatchBSSID, bPacketToSelf);
5218                 }
5219                 if(WLAN_FC_GET_FRAMETYPE(fc) == IEEE80211_STYPE_BLOCKACK)
5220                 {
5221                         if((eqMacAddr(praddr,dev->dev_addr)))
5222                                 bToSelfBA = true;
5223                                 //DbgPrint("BlockAck, MatchBSSID = %d, ToSelf = %d \n", bPacketMatchBSSID, bPacketToSelf);
5224                 }
5225
5226
5227
5228         if(bpacket_match_bssid)
5229         {
5230                 priv->stats.numpacket_matchbssid++;
5231         }
5232         if(bpacket_toself){
5233                 priv->stats.numpacket_toself++;
5234         }
5235         //
5236         // Process PHY information for previous packet (RSSI/PWDB/EVM)
5237         //
5238         // Because phy information is contained in the last packet of AMPDU only, so driver
5239         // should process phy information of previous packet
5240         rtl8192_process_phyinfo(priv, tmp_buf, &previous_stats, pstats);
5241         rtl8192_query_rxphystatus(priv, pstats, pdrvinfo, &previous_stats, bpacket_match_bssid,bpacket_toself,bPacketBeacon,bToSelfBA);
5242         rtl8192_record_rxdesc_forlateruse(pstats, &previous_stats);
5243
5244 }
5245
5246 /**
5247 * Function:     UpdateReceivedRateHistogramStatistics
5248 * Overview:     Recored down the received data rate
5249 *
5250 * Input:
5251 *       struct net_device *dev
5252 *       struct ieee80211_rx_stats *stats
5253 *
5254 * Output:
5255 *
5256 *                       (priv->stats.ReceivedRateHistogram[] is updated)
5257 * Return:
5258 *               None
5259 */
5260 void
5261 UpdateReceivedRateHistogramStatistics8190(
5262         struct net_device *dev,
5263         struct ieee80211_rx_stats *stats
5264         )
5265 {
5266         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
5267         u32 rcvType=1;   //0: Total, 1:OK, 2:CRC, 3:ICV
5268         u32 rateIndex;
5269         u32 preamble_guardinterval;  //1: short preamble/GI, 0: long preamble/GI
5270
5271
5272         if(stats->bCRC)
5273         rcvType = 2;
5274         else if(stats->bICV)
5275         rcvType = 3;
5276
5277         if(stats->bShortPreamble)
5278         preamble_guardinterval = 1;// short
5279         else
5280         preamble_guardinterval = 0;// long
5281
5282         switch(stats->rate)
5283         {
5284                 //
5285                 // CCK rate
5286                 //
5287                 case MGN_1M:    rateIndex = 0;  break;
5288                 case MGN_2M:    rateIndex = 1;  break;
5289                 case MGN_5_5M:  rateIndex = 2;  break;
5290                 case MGN_11M:   rateIndex = 3;  break;
5291                 //
5292                 // Legacy OFDM rate
5293                 //
5294                 case MGN_6M:    rateIndex = 4;  break;
5295                 case MGN_9M:    rateIndex = 5;  break;
5296                 case MGN_12M:   rateIndex = 6;  break;
5297                 case MGN_18M:   rateIndex = 7;  break;
5298                 case MGN_24M:   rateIndex = 8;  break;
5299                 case MGN_36M:   rateIndex = 9;  break;
5300                 case MGN_48M:   rateIndex = 10; break;
5301                 case MGN_54M:   rateIndex = 11; break;
5302                 //
5303                 // 11n High throughput rate
5304                 //
5305                 case MGN_MCS0:  rateIndex = 12; break;
5306                 case MGN_MCS1:  rateIndex = 13; break;
5307                 case MGN_MCS2:  rateIndex = 14; break;
5308                 case MGN_MCS3:  rateIndex = 15; break;
5309                 case MGN_MCS4:  rateIndex = 16; break;
5310                 case MGN_MCS5:  rateIndex = 17; break;
5311                 case MGN_MCS6:  rateIndex = 18; break;
5312                 case MGN_MCS7:  rateIndex = 19; break;
5313                 case MGN_MCS8:  rateIndex = 20; break;
5314                 case MGN_MCS9:  rateIndex = 21; break;
5315                 case MGN_MCS10: rateIndex = 22; break;
5316                 case MGN_MCS11: rateIndex = 23; break;
5317                 case MGN_MCS12: rateIndex = 24; break;
5318                 case MGN_MCS13: rateIndex = 25; break;
5319                 case MGN_MCS14: rateIndex = 26; break;
5320                 case MGN_MCS15: rateIndex = 27; break;
5321                 default:        rateIndex = 28; break;
5322         }
5323     priv->stats.received_preamble_GI[preamble_guardinterval][rateIndex]++;
5324     priv->stats.received_rate_histogram[0][rateIndex]++; //total
5325     priv->stats.received_rate_histogram[rcvType][rateIndex]++;
5326 }
5327
5328
5329 void query_rxdesc_status(struct sk_buff *skb, struct ieee80211_rx_stats *stats, bool bIsRxAggrSubframe)
5330 {
5331         rtl8192_rx_info *info = (struct rtl8192_rx_info *)skb->cb;
5332         struct net_device *dev=info->dev;
5333         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
5334         //rx_desc_819x_usb *desc = (rx_desc_819x_usb *)skb->data;
5335         rx_drvinfo_819x_usb  *driver_info = NULL;
5336
5337         //
5338         //Get Rx Descriptor Information
5339         //
5340 #ifdef USB_RX_AGGREGATION_SUPPORT
5341         if (bIsRxAggrSubframe)
5342         {
5343                 rx_desc_819x_usb_aggr_subframe *desc = (rx_desc_819x_usb_aggr_subframe *)skb->data;
5344                 stats->Length = desc->Length ;
5345                 stats->RxDrvInfoSize = desc->RxDrvInfoSize;
5346                 stats->RxBufShift = 0; //RxBufShift = 2 in RxDesc, but usb didn't shift bytes in fact.
5347                 stats->bICV = desc->ICV;
5348                 stats->bCRC = desc->CRC32;
5349                 stats->bHwError = stats->bCRC|stats->bICV;
5350                 stats->Decrypted = !desc->SWDec;//RTL8190 set this bit to indicate that Hw does not decrypt packet
5351         } else
5352 #endif
5353         {
5354                 rx_desc_819x_usb *desc = (rx_desc_819x_usb *)skb->data;
5355
5356                 stats->Length = desc->Length;
5357                 stats->RxDrvInfoSize = desc->RxDrvInfoSize;
5358                 stats->RxBufShift = 0;//desc->Shift&0x03;
5359                 stats->bICV = desc->ICV;
5360                 stats->bCRC = desc->CRC32;
5361                 stats->bHwError = stats->bCRC|stats->bICV;
5362                 //RTL8190 set this bit to indicate that Hw does not decrypt packet
5363                 stats->Decrypted = !desc->SWDec;
5364         }
5365
5366         if((priv->ieee80211->pHTInfo->bCurrentHTSupport == true) && (priv->ieee80211->pairwise_key_type == KEY_TYPE_CCMP))
5367         {
5368                 stats->bHwError = false;
5369         }
5370         else
5371         {
5372                 stats->bHwError = stats->bCRC|stats->bICV;
5373         }
5374
5375         if(stats->Length < 24 || stats->Length > MAX_8192U_RX_SIZE)
5376                 stats->bHwError |= 1;
5377         //
5378         //Get Driver Info
5379         //
5380         // TODO: Need to verify it on FGPA platform
5381         //Driver info are written to the RxBuffer following rx desc
5382         if (stats->RxDrvInfoSize != 0) {
5383                 driver_info = (rx_drvinfo_819x_usb *)(skb->data + sizeof(rx_desc_819x_usb) + \
5384                                 stats->RxBufShift);
5385                 /* unit: 0.5M */
5386                 /* TODO */
5387                 if(!stats->bHwError){
5388                         u8      ret_rate;
5389                         ret_rate = HwRateToMRate90(driver_info->RxHT, driver_info->RxRate);
5390                         if(ret_rate == 0xff)
5391                         {
5392                                 // Abnormal Case: Receive CRC OK packet with Rx descriptor indicating non supported rate.
5393                                 // Special Error Handling here, 2008.05.16, by Emily
5394
5395                                 stats->bHwError = 1;
5396                                 stats->rate = MGN_1M;   //Set 1M rate by default
5397                         }else
5398                         {
5399                                 stats->rate = ret_rate;
5400                         }
5401                 }
5402                 else
5403                         stats->rate = 0x02;
5404
5405                 stats->bShortPreamble = driver_info->SPLCP;
5406
5407
5408                 UpdateReceivedRateHistogramStatistics8190(dev, stats);
5409
5410                 stats->bIsAMPDU = (driver_info->PartAggr==1);
5411                 stats->bFirstMPDU = (driver_info->PartAggr==1) && (driver_info->FirstAGGR==1);
5412                 stats->TimeStampLow = driver_info->TSFL;
5413                 // xiong mask it, 070514
5414                 //pRfd->Status.TimeStampHigh = PlatformEFIORead4Byte(Adapter, TSFR+4);
5415                 // stats->TimeStampHigh = read_nic_dword(dev,  TSFR+4);
5416
5417                 UpdateRxPktTimeStamp8190(dev, stats);
5418
5419                 //
5420                 // Rx A-MPDU
5421                 //
5422                 if(driver_info->FirstAGGR==1 || driver_info->PartAggr == 1)
5423                         RT_TRACE(COMP_RXDESC, "driver_info->FirstAGGR = %d, driver_info->PartAggr = %d\n",
5424                                         driver_info->FirstAGGR, driver_info->PartAggr);
5425
5426         }
5427
5428         skb_pull(skb,sizeof(rx_desc_819x_usb));
5429         //
5430         // Get Total offset of MPDU Frame Body
5431         //
5432         if((stats->RxBufShift + stats->RxDrvInfoSize) > 0) {
5433                 stats->bShift = 1;
5434                 skb_pull(skb,stats->RxBufShift + stats->RxDrvInfoSize);
5435         }
5436
5437 #ifdef USB_RX_AGGREGATION_SUPPORT
5438         /* for the rx aggregated sub frame, the redundant space truelly contained in the packet */
5439         if(bIsRxAggrSubframe) {
5440                 skb_pull(skb, 8);
5441         }
5442 #endif
5443         /* for debug 2008.5.29 */
5444
5445         //added by vivi, for MP, 20080108
5446         stats->RxIs40MHzPacket = driver_info->BW;
5447         if(stats->RxDrvInfoSize != 0)
5448                 TranslateRxSignalStuff819xUsb(skb, stats, driver_info);
5449
5450 }
5451
5452 u32 GetRxPacketShiftBytes819xUsb(struct ieee80211_rx_stats  *Status, bool bIsRxAggrSubframe)
5453 {
5454 #ifdef USB_RX_AGGREGATION_SUPPORT
5455         if (bIsRxAggrSubframe)
5456                 return (sizeof(rx_desc_819x_usb) + Status->RxDrvInfoSize
5457                         + Status->RxBufShift + 8);
5458         else
5459 #endif
5460                 return (sizeof(rx_desc_819x_usb) + Status->RxDrvInfoSize
5461                                 + Status->RxBufShift);
5462 }
5463
5464 void rtl8192_rx_nomal(struct sk_buff* skb)
5465 {
5466         rtl8192_rx_info *info = (struct rtl8192_rx_info *)skb->cb;
5467         struct net_device *dev=info->dev;
5468         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
5469         struct ieee80211_rx_stats stats = {
5470                 .signal = 0,
5471                 .noise = -98,
5472                 .rate = 0,
5473                 //      .mac_time = jiffies,
5474                 .freq = IEEE80211_24GHZ_BAND,
5475         };
5476         u32 rx_pkt_len = 0;
5477         struct ieee80211_hdr_1addr *ieee80211_hdr = NULL;
5478         bool unicast_packet = false;
5479 #ifdef USB_RX_AGGREGATION_SUPPORT
5480         struct sk_buff *agg_skb = NULL;
5481         u32  TotalLength = 0;
5482         u32  TempDWord = 0;
5483         u32  PacketLength = 0;
5484         u32  PacketOccupiedLendth = 0;
5485         u8   TempByte = 0;
5486         u32  PacketShiftBytes = 0;
5487         rx_desc_819x_usb_aggr_subframe *RxDescr = NULL;
5488         u8  PaddingBytes = 0;
5489         //add just for testing
5490         u8   testing;
5491
5492 #endif
5493
5494         /* 20 is for ps-poll */
5495         if((skb->len >=(20 + sizeof(rx_desc_819x_usb))) && (skb->len < RX_URB_SIZE)) {
5496 #ifdef USB_RX_AGGREGATION_SUPPORT
5497                 TempByte = *(skb->data + sizeof(rx_desc_819x_usb));
5498 #endif
5499                 /* first packet should not contain Rx aggregation header */
5500                 query_rxdesc_status(skb, &stats, false);
5501                 /* TODO */
5502                 /* hardware related info */
5503 #ifdef USB_RX_AGGREGATION_SUPPORT
5504                 if (TempByte & BIT0) {
5505                         agg_skb = skb;
5506                         //TotalLength = agg_skb->len - 4; /*sCrcLng*/
5507                         TotalLength = stats.Length - 4; /*sCrcLng*/
5508                         //RT_TRACE(COMP_RECV, "%s:first aggregated packet!Length=%d\n",__FUNCTION__,TotalLength);
5509                         /* though the head pointer has passed this position  */
5510                         TempDWord = *(u32 *)(agg_skb->data - 4);
5511                         PacketLength = (u16)(TempDWord & 0x3FFF); /*sCrcLng*/
5512                         skb = dev_alloc_skb(PacketLength);
5513                         memcpy(skb_put(skb,PacketLength),agg_skb->data,PacketLength);
5514                         PacketShiftBytes = GetRxPacketShiftBytes819xUsb(&stats, false);
5515                 }
5516 #endif
5517                 /* Process the MPDU recevied */
5518                 skb_trim(skb, skb->len - 4/*sCrcLng*/);
5519
5520                 rx_pkt_len = skb->len;
5521                 ieee80211_hdr = (struct ieee80211_hdr_1addr *)skb->data;
5522                 unicast_packet = false;
5523                 if(is_broadcast_ether_addr(ieee80211_hdr->addr1)) {
5524                         //TODO
5525                 }else if(is_multicast_ether_addr(ieee80211_hdr->addr1)){
5526                         //TODO
5527                 }else {
5528                         /* unicast packet */
5529                         unicast_packet = true;
5530                 }
5531
5532                 if(!ieee80211_rx(priv->ieee80211,skb, &stats)) {
5533                         dev_kfree_skb_any(skb);
5534                 } else {
5535                         priv->stats.rxoktotal++;
5536                         if(unicast_packet) {
5537                                 priv->stats.rxbytesunicast += rx_pkt_len;
5538                         }
5539                 }
5540 #ifdef USB_RX_AGGREGATION_SUPPORT
5541                 testing = 1;
5542                 // (PipeIndex == 0) && (TempByte & BIT0) => TotalLength > 0.
5543                 if (TotalLength > 0) {
5544                         PacketOccupiedLendth = PacketLength + (PacketShiftBytes + 8);
5545                         if ((PacketOccupiedLendth & 0xFF) != 0)
5546                                 PacketOccupiedLendth = (PacketOccupiedLendth & 0xFFFFFF00) + 256;
5547                         PacketOccupiedLendth -= 8;
5548                         TempDWord = PacketOccupiedLendth - PacketShiftBytes; /*- PacketLength */
5549                         if (agg_skb->len > TempDWord)
5550                                 skb_pull(agg_skb, TempDWord);
5551                         else
5552                                 agg_skb->len = 0;
5553
5554                         while (agg_skb->len>=GetRxPacketShiftBytes819xUsb(&stats, true)) {
5555                                 u8 tmpCRC = 0, tmpICV = 0;
5556                                 //RT_TRACE(COMP_RECV,"%s:aggred pkt,total_len = %d\n",__FUNCTION__,agg_skb->len);
5557                                 RxDescr = (rx_desc_819x_usb_aggr_subframe *)(agg_skb->data);
5558                                 tmpCRC = RxDescr->CRC32;
5559                                 tmpICV = RxDescr->ICV;
5560                                 memcpy(agg_skb->data, &agg_skb->data[44], 2);
5561                                 RxDescr->CRC32 = tmpCRC;
5562                                 RxDescr->ICV = tmpICV;
5563
5564                                 memset(&stats, 0, sizeof(struct ieee80211_rx_stats));
5565                                 stats.signal = 0;
5566                                 stats.noise = -98;
5567                                 stats.rate = 0;
5568                                 stats.freq = IEEE80211_24GHZ_BAND;
5569                                 query_rxdesc_status(agg_skb, &stats, true);
5570                                 PacketLength = stats.Length;
5571
5572                                 if(PacketLength > agg_skb->len) {
5573                                         break;
5574                                 }
5575                                 /* Process the MPDU recevied */
5576                                 skb = dev_alloc_skb(PacketLength);
5577                                 memcpy(skb_put(skb,PacketLength),agg_skb->data, PacketLength);
5578                                 skb_trim(skb, skb->len - 4/*sCrcLng*/);
5579
5580                                 rx_pkt_len = skb->len;
5581                                 ieee80211_hdr = (struct ieee80211_hdr_1addr *)skb->data;
5582                                 unicast_packet = false;
5583                                 if(is_broadcast_ether_addr(ieee80211_hdr->addr1)) {
5584                                         //TODO
5585                                 }else if(is_multicast_ether_addr(ieee80211_hdr->addr1)){
5586                                         //TODO
5587                                 }else {
5588                                         /* unicast packet */
5589                                         unicast_packet = true;
5590                                 }
5591                                 if(!ieee80211_rx(priv->ieee80211,skb, &stats)) {
5592                                         dev_kfree_skb_any(skb);
5593                                 } else {
5594                                         priv->stats.rxoktotal++;
5595                                         if(unicast_packet) {
5596                                                 priv->stats.rxbytesunicast += rx_pkt_len;
5597                                         }
5598                                 }
5599                                 /* should trim the packet which has been copied to target skb */
5600                                 skb_pull(agg_skb, PacketLength);
5601                                 PacketShiftBytes = GetRxPacketShiftBytes819xUsb(&stats, true);
5602                                 PacketOccupiedLendth = PacketLength + PacketShiftBytes;
5603                                 if ((PacketOccupiedLendth & 0xFF) != 0) {
5604                                         PaddingBytes = 256 - (PacketOccupiedLendth & 0xFF);
5605                                         if (agg_skb->len > PaddingBytes)
5606                                                 skb_pull(agg_skb, PaddingBytes);
5607                                         else
5608                                                 agg_skb->len = 0;
5609                                 }
5610                         }
5611                         dev_kfree_skb(agg_skb);
5612                 }
5613 #endif
5614         } else {
5615                 priv->stats.rxurberr++;
5616                 printk("actual_length:%d\n", skb->len);
5617                 dev_kfree_skb_any(skb);
5618         }
5619
5620 }
5621
5622 void
5623 rtl819xusb_process_received_packet(
5624         struct net_device *dev,
5625         struct ieee80211_rx_stats *pstats
5626         )
5627 {
5628 //      bool bfreerfd=false, bqueued=false;
5629         u8*     frame;
5630         u16     frame_len=0;
5631         struct r8192_priv *priv = ieee80211_priv(dev);
5632 //      u8                      index = 0;
5633 //      u8                      TID = 0;
5634         //u16                   seqnum = 0;
5635         //PRX_TS_RECORD pts = NULL;
5636
5637         // Get shifted bytes of Starting address of 802.11 header. 2006.09.28, by Emily
5638         //porting by amy 080508
5639         pstats->virtual_address += get_rxpacket_shiftbytes_819xusb(pstats);
5640         frame = pstats->virtual_address;
5641         frame_len = pstats->packetlength;
5642 #ifdef TODO     // by amy about HCT
5643         if(!Adapter->bInHctTest)
5644                 CountRxErrStatistics(Adapter, pRfd);
5645 #endif
5646         {
5647         #ifdef ENABLE_PS  //by amy for adding ps function in future
5648                 RT_RF_POWER_STATE rtState;
5649                 // When RF is off, we should not count the packet for hw/sw synchronize
5650                 // reason, ie. there may be a duration while sw switch is changed and hw
5651                 // switch is being changed. 2006.12.04, by shien chang.
5652                 Adapter->HalFunc.GetHwRegHandler(Adapter, HW_VAR_RF_STATE, (u8* )(&rtState));
5653                 if (rtState == eRfOff)
5654                 {
5655                         return;
5656                 }
5657         #endif
5658         priv->stats.rxframgment++;
5659
5660         }
5661 #ifdef TODO
5662         RmMonitorSignalStrength(Adapter, pRfd);
5663 #endif
5664         /* 2007/01/16 MH Add RX command packet handle here. */
5665         /* 2007/03/01 MH We have to release RFD and return if rx pkt is cmd pkt. */
5666         if (rtl819xusb_rx_command_packet(dev, pstats))
5667         {
5668                 return;
5669         }
5670
5671 #ifdef SW_CRC_CHECK
5672         SwCrcCheck();
5673 #endif
5674
5675
5676 }
5677
5678 void query_rx_cmdpkt_desc_status(struct sk_buff *skb, struct ieee80211_rx_stats *stats)
5679 {
5680 //      rtl8192_rx_info *info = (struct rtl8192_rx_info *)skb->cb;
5681 //      struct net_device *dev=info->dev;
5682 //      struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
5683         rx_desc_819x_usb *desc = (rx_desc_819x_usb *)skb->data;
5684 //      rx_drvinfo_819x_usb  *driver_info;
5685
5686         //
5687         //Get Rx Descriptor Information
5688         //
5689         stats->virtual_address = (u8*)skb->data;
5690         stats->Length = desc->Length;
5691         stats->RxDrvInfoSize = 0;
5692         stats->RxBufShift = 0;
5693         stats->packetlength = stats->Length-scrclng;
5694         stats->fraglength = stats->packetlength;
5695         stats->fragoffset = 0;
5696         stats->ntotalfrag = 1;
5697 }
5698
5699
5700 void rtl8192_rx_cmd(struct sk_buff *skb)
5701 {
5702         struct rtl8192_rx_info *info = (struct rtl8192_rx_info *)skb->cb;
5703         struct net_device *dev = info->dev;
5704         //int ret;
5705 //      struct urb *rx_urb = info->urb;
5706         /* TODO */
5707         struct ieee80211_rx_stats stats = {
5708                 .signal = 0,
5709                 .noise = -98,
5710                 .rate = 0,
5711                 //      .mac_time = jiffies,
5712                 .freq = IEEE80211_24GHZ_BAND,
5713         };
5714
5715         if((skb->len >=(20 + sizeof(rx_desc_819x_usb))) && (skb->len < RX_URB_SIZE))
5716         {
5717
5718                 query_rx_cmdpkt_desc_status(skb,&stats);
5719                 // this is to be done by amy 080508     prfd->queue_id = 1;
5720
5721
5722                 //
5723                 //  Process the command packet received.
5724                 //
5725
5726                 rtl819xusb_process_received_packet(dev,&stats);
5727
5728                 dev_kfree_skb_any(skb);
5729         }
5730         else
5731                 ;
5732
5733
5734 }
5735
5736 void rtl8192_irq_rx_tasklet(struct r8192_priv *priv)
5737 {
5738         struct sk_buff *skb;
5739         struct rtl8192_rx_info *info;
5740
5741         while (NULL != (skb = skb_dequeue(&priv->skb_queue))) {
5742                 info = (struct rtl8192_rx_info *)skb->cb;
5743                 switch (info->out_pipe) {
5744                 /* Nomal packet pipe */
5745                         case 3:
5746                                 //RT_TRACE(COMP_RECV, "normal in-pipe index(%d)\n",info->out_pipe);
5747                                 priv->IrpPendingCount--;
5748                                 rtl8192_rx_nomal(skb);
5749                                 break;
5750
5751                                 /* Command packet pipe */
5752                         case 9:
5753                                 RT_TRACE(COMP_RECV, "command in-pipe index(%d)\n",\
5754                                                 info->out_pipe);
5755
5756                                 rtl8192_rx_cmd(skb);
5757                                 break;
5758
5759                         default: /* should never get here! */
5760                                 RT_TRACE(COMP_ERR, "Unknown in-pipe index(%d)\n",\
5761                                                 info->out_pipe);
5762                                 dev_kfree_skb(skb);
5763                                 break;
5764
5765                 }
5766         }
5767 }
5768
5769 static const struct net_device_ops rtl8192_netdev_ops = {
5770         .ndo_open               = rtl8192_open,
5771         .ndo_stop               = rtl8192_close,
5772         .ndo_get_stats          = rtl8192_stats,
5773         .ndo_tx_timeout         = tx_timeout,
5774         .ndo_do_ioctl           = rtl8192_ioctl,
5775         .ndo_set_multicast_list = r8192_set_multicast,
5776         .ndo_set_mac_address    = r8192_set_mac_adr,
5777         .ndo_validate_addr      = eth_validate_addr,
5778         .ndo_change_mtu         = eth_change_mtu,
5779         .ndo_start_xmit         = ieee80211_xmit,
5780 };
5781
5782
5783 /****************************************************************************
5784      ---------------------------- USB_STUFF---------------------------
5785 *****************************************************************************/
5786
5787 static int __devinit rtl8192_usb_probe(struct usb_interface *intf,
5788                          const struct usb_device_id *id)
5789 {
5790 //      unsigned long ioaddr = 0;
5791         struct net_device *dev = NULL;
5792         struct r8192_priv *priv= NULL;
5793         struct usb_device *udev = interface_to_usbdev(intf);
5794         RT_TRACE(COMP_INIT, "Oops: i'm coming\n");
5795
5796         dev = alloc_ieee80211(sizeof(struct r8192_priv));
5797
5798
5799         usb_set_intfdata(intf, dev);
5800         SET_NETDEV_DEV(dev, &intf->dev);
5801         priv = ieee80211_priv(dev);
5802         priv->ieee80211 = netdev_priv(dev);
5803         priv->udev=udev;
5804
5805         dev->netdev_ops = &rtl8192_netdev_ops;
5806
5807          //DMESG("Oops: i'm coming\n");
5808 #if WIRELESS_EXT >= 12
5809 #if WIRELESS_EXT < 17
5810         dev->get_wireless_stats = r8192_get_wireless_stats;
5811 #endif
5812         dev->wireless_handlers = (struct iw_handler_def *) &r8192_wx_handlers_def;
5813 #endif
5814         dev->type=ARPHRD_ETHER;
5815
5816         dev->watchdog_timeo = HZ*3;     //modified by john, 0805
5817
5818         if (dev_alloc_name(dev, ifname) < 0){
5819                 RT_TRACE(COMP_INIT, "Oops: devname already taken! Trying wlan%%d...\n");
5820                 ifname = "wlan%d";
5821                 dev_alloc_name(dev, ifname);
5822         }
5823
5824         RT_TRACE(COMP_INIT, "Driver probe completed1\n");
5825         if(rtl8192_init(dev)!=0){
5826                 RT_TRACE(COMP_ERR, "Initialization failed");
5827                 goto fail;
5828         }
5829         netif_carrier_off(dev);
5830         netif_stop_queue(dev);
5831
5832         register_netdev(dev);
5833         RT_TRACE(COMP_INIT, "dev name=======> %s\n",dev->name);
5834         rtl8192_proc_init_one(dev);
5835
5836
5837         RT_TRACE(COMP_INIT, "Driver probe completed\n");
5838         return 0;
5839
5840
5841 fail:
5842         free_ieee80211(dev);
5843
5844         RT_TRACE(COMP_ERR, "wlan driver load failed\n");
5845         return -ENODEV;
5846
5847 }
5848
5849 //detach all the work and timer structure declared or inititialize in r8192U_init function.
5850 void rtl8192_cancel_deferred_work(struct r8192_priv* priv)
5851 {
5852
5853         cancel_work_sync(&priv->reset_wq);
5854         cancel_delayed_work(&priv->watch_dog_wq);
5855         cancel_delayed_work(&priv->update_beacon_wq);
5856         cancel_work_sync(&priv->qos_activate);
5857         //cancel_work_sync(&priv->SetBWModeWorkItem);
5858         //cancel_work_sync(&priv->SwChnlWorkItem);
5859
5860 }
5861
5862
5863 static void __devexit rtl8192_usb_disconnect(struct usb_interface *intf)
5864 {
5865         struct net_device *dev = usb_get_intfdata(intf);
5866
5867         struct r8192_priv *priv = ieee80211_priv(dev);
5868         if(dev){
5869
5870                 unregister_netdev(dev);
5871
5872                 RT_TRACE(COMP_DOWN, "=============>wlan driver to be removed\n");
5873                 rtl8192_proc_remove_one(dev);
5874
5875                         rtl8192_down(dev);
5876                 if (priv->pFirmware)
5877                 {
5878                         kfree(priv->pFirmware);
5879                         priv->pFirmware = NULL;
5880                 }
5881         //      priv->rf_close(dev);
5882 //              rtl8192_SetRFPowerState(dev, eRfOff);
5883                 rtl8192_usb_deleteendpoints(dev);
5884                 destroy_workqueue(priv->priv_wq);
5885                 //rtl8192_irq_disable(dev);
5886                 //rtl8192_reset(dev);
5887                 mdelay(10);
5888
5889         }
5890         free_ieee80211(dev);
5891         RT_TRACE(COMP_DOWN, "wlan driver removed\n");
5892 }
5893
5894 /* fun with the built-in ieee80211 stack... */
5895 extern int ieee80211_debug_init(void);
5896 extern void ieee80211_debug_exit(void);
5897 extern int ieee80211_crypto_init(void);
5898 extern void ieee80211_crypto_deinit(void);
5899 extern int ieee80211_crypto_tkip_init(void);
5900 extern void ieee80211_crypto_tkip_exit(void);
5901 extern int ieee80211_crypto_ccmp_init(void);
5902 extern void ieee80211_crypto_ccmp_exit(void);
5903 extern int ieee80211_crypto_wep_init(void);
5904 extern void ieee80211_crypto_wep_exit(void);
5905
5906 static int __init rtl8192_usb_module_init(void)
5907 {
5908         int ret;
5909
5910 #ifdef CONFIG_IEEE80211_DEBUG
5911         ret = ieee80211_debug_init();
5912         if (ret) {
5913                 printk(KERN_ERR "ieee80211_debug_init() failed %d\n", ret);
5914                 return ret;
5915         }
5916 #endif
5917         ret = ieee80211_crypto_init();
5918         if (ret) {
5919                 printk(KERN_ERR "ieee80211_crypto_init() failed %d\n", ret);
5920                 return ret;
5921         }
5922
5923         ret = ieee80211_crypto_tkip_init();
5924         if (ret) {
5925                 printk(KERN_ERR "ieee80211_crypto_tkip_init() failed %d\n",
5926                         ret);
5927                 return ret;
5928         }
5929
5930         ret = ieee80211_crypto_ccmp_init();
5931         if (ret) {
5932                 printk(KERN_ERR "ieee80211_crypto_ccmp_init() failed %d\n",
5933                         ret);
5934                 return ret;
5935         }
5936
5937         ret = ieee80211_crypto_wep_init();
5938         if (ret) {
5939                 printk(KERN_ERR "ieee80211_crypto_wep_init() failed %d\n", ret);
5940                 return ret;
5941         }
5942
5943         printk(KERN_INFO "\nLinux kernel driver for RTL8192 based WLAN cards\n");
5944         printk(KERN_INFO "Copyright (c) 2007-2008, Realsil Wlan\n");
5945         RT_TRACE(COMP_INIT, "Initializing module");
5946         RT_TRACE(COMP_INIT, "Wireless extensions version %d", WIRELESS_EXT);
5947         rtl8192_proc_module_init();
5948         return usb_register(&rtl8192_usb_driver);
5949 }
5950
5951
5952 static void __exit rtl8192_usb_module_exit(void)
5953 {
5954         usb_deregister(&rtl8192_usb_driver);
5955
5956         RT_TRACE(COMP_DOWN, "Exiting");
5957 //      rtl8192_proc_module_remove();
5958 }
5959
5960
5961 void rtl8192_try_wake_queue(struct net_device *dev, int pri)
5962 {
5963         unsigned long flags;
5964         short enough_desc;
5965         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
5966
5967         spin_lock_irqsave(&priv->tx_lock,flags);
5968         enough_desc = check_nic_enough_desc(dev,pri);
5969         spin_unlock_irqrestore(&priv->tx_lock,flags);
5970
5971         if(enough_desc)
5972                 ieee80211_wake_queue(priv->ieee80211);
5973 }
5974
5975 void EnableHWSecurityConfig8192(struct net_device *dev)
5976 {
5977         u8 SECR_value = 0x0;
5978         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
5979          struct ieee80211_device* ieee = priv->ieee80211;
5980         SECR_value = SCR_TxEncEnable | SCR_RxDecEnable;
5981         if (((KEY_TYPE_WEP40 == ieee->pairwise_key_type) || (KEY_TYPE_WEP104 == ieee->pairwise_key_type)) && (priv->ieee80211->auth_mode != 2))
5982         {
5983                 SECR_value |= SCR_RxUseDK;
5984                 SECR_value |= SCR_TxUseDK;
5985         }
5986         else if ((ieee->iw_mode == IW_MODE_ADHOC) && (ieee->pairwise_key_type & (KEY_TYPE_CCMP | KEY_TYPE_TKIP)))
5987         {
5988                 SECR_value |= SCR_RxUseDK;
5989                 SECR_value |= SCR_TxUseDK;
5990         }
5991         //add HWSec active enable here.
5992 //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
5993
5994         ieee->hwsec_active = 1;
5995
5996         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
5997         {
5998                 ieee->hwsec_active = 0;
5999                 SECR_value &= ~SCR_RxDecEnable;
6000         }
6001         RT_TRACE(COMP_SEC,"%s:, hwsec:%d, pairwise_key:%d, SECR_value:%x\n", __FUNCTION__, \
6002                         ieee->hwsec_active, ieee->pairwise_key_type, SECR_value);
6003         {
6004                 write_nic_byte(dev, SECR,  SECR_value);//SECR_value |  SCR_UseDK );
6005         }
6006 }
6007
6008
6009 void setKey(    struct net_device *dev,
6010                 u8 EntryNo,
6011                 u8 KeyIndex,
6012                 u16 KeyType,
6013                 u8 *MacAddr,
6014                 u8 DefaultKey,
6015                 u32 *KeyContent )
6016 {
6017         u32 TargetCommand = 0;
6018         u32 TargetContent = 0;
6019         u16 usConfig = 0;
6020         u8 i;
6021         if (EntryNo >= TOTAL_CAM_ENTRY)
6022                 RT_TRACE(COMP_ERR, "cam entry exceeds in setKey()\n");
6023
6024         RT_TRACE(COMP_SEC, "====>to setKey(), dev:%p, EntryNo:%d, KeyIndex:%d, KeyType:%d, MacAddr%pM\n", dev,EntryNo, KeyIndex, KeyType, MacAddr);
6025
6026         if (DefaultKey)
6027                 usConfig |= BIT15 | (KeyType<<2);
6028         else
6029                 usConfig |= BIT15 | (KeyType<<2) | KeyIndex;
6030 //      usConfig |= BIT15 | (KeyType<<2) | (DefaultKey<<5) | KeyIndex;
6031
6032
6033         for(i=0 ; i<CAM_CONTENT_COUNT; i++){
6034                 TargetCommand  = i+CAM_CONTENT_COUNT*EntryNo;
6035                 TargetCommand |= BIT31|BIT16;
6036
6037                 if(i==0){//MAC|Config
6038                         TargetContent = (u32)(*(MacAddr+0)) << 16|
6039                                         (u32)(*(MacAddr+1)) << 24|
6040                                         (u32)usConfig;
6041
6042                         write_nic_dword(dev, WCAMI, TargetContent);
6043                         write_nic_dword(dev, RWCAM, TargetCommand);
6044         //              printk("setkey cam =%8x\n", read_cam(dev, i+6*EntryNo));
6045                 }
6046                 else if(i==1){//MAC
6047                         TargetContent = (u32)(*(MacAddr+2))      |
6048                                         (u32)(*(MacAddr+3)) <<  8|
6049                                         (u32)(*(MacAddr+4)) << 16|
6050                                         (u32)(*(MacAddr+5)) << 24;
6051                         write_nic_dword(dev, WCAMI, TargetContent);
6052                         write_nic_dword(dev, RWCAM, TargetCommand);
6053                 }
6054                 else {
6055                         //Key Material
6056                         if(KeyContent !=NULL){
6057                         write_nic_dword(dev, WCAMI, (u32)(*(KeyContent+i-2)) );
6058                         write_nic_dword(dev, RWCAM, TargetCommand);
6059                 }
6060         }
6061         }
6062
6063 }
6064
6065 /***************************************************************************
6066      ------------------- module init / exit stubs ----------------
6067 ****************************************************************************/
6068 module_init(rtl8192_usb_module_init);
6069 module_exit(rtl8192_usb_module_exit);