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